MODULE 1 - 2 [ REACT JS NOTES ] BASICS FOR ALL WEB DEVELOPMENT
REACT NOTES:
BASICS FOR ALL WEB DEVELOPMENT:
Module 1: HTML, CSS, Javascript, Client Side JQuery
CREATING A HTML WEBPAGE
a. Create an HTML file.
An HTML file is simply a text file saved with an .html or .htm extension (i.e. as opposed to a .txt extension).
1. Open up your computer's normal plain text editor (this will probably be Notepad if you're using Windows or TextEdit if you're using a Mac). You could use a specialized HTML editor such as DreamWeaver or FrontPage if you prefer.
2. Create a new file (if one wasn't already created)
3. Save the file as html_tutorial_example.html
b.Type some HTML code.
Type the following code:
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd" >
< html >
< head >
< title > HTML Tutorial Example </title >
</ head >
< body >
< p > Less than 5 minutes into this HTML tutorial and I've already created my first homepage! </p >
</ body >
</ html >
c. View the result in your browser.
HTML ELEMENTS:
HTML elements are the fundamentals of HTML. HTML documents are simply a text file made up of HTML elements. These elements are defined using HTML tags. HTML tags tell your browser which elements to present and how to present them. Where the element appears is determined by the order in which the tags appear.
lets look more closely at the following example.
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd" >
< html >
< head >
< title > HTML Tutorial Example </title >
</ head >
< body >
< p > Less than 5 minutes into this HTML tutorial and I've already created my first homepage!
</ body >
</ html >
Explanation of the above code:
The < !DOCTYPE... > element tells the browser which version of HTML the document is using.
The < html> element can be thought of as a container that all other tags sit inside (except for the !DOCTYPE tag).
The < head > tag contains information that is not normally viewable within your browser (such as meta tags, JavaScript and CSS), although the < title > tag is an exception to this. The content of the < title > tag is displayed in the browser's title bar (right at the very top of the browser).
The < body > tag is the main area for your content. This is where most of your code (and viewable elements) will go.
The < p > tag declares a paragraph. This contains the body text.
HTML Element Syntax
An HTML element starts with a start tag / opening tag
An HTML element ends with an end tag / closing tag
The element content is everything between the start and the end tag
Some HTML elements have empty content
Empty elements are closed in the start tag
Most HTML elements can have attributes
HTML ATTRIBUTES:
HTML elements can have attributes
Attributes provide additional information about an element
Attributes are always specified in the start tag
Attributes come in name/value pairs like: name="value"
Example
Consider this example:
< body style="background-color:orange" >
HTML Attributes Reference
Below is a list of some attributes that are standard for most HTML elements:
HTML HEADINGS:
There is a special tag for specifying headings in HTML. There are 6 levels of headings in HTML ranging from h1 for the most important, to h6 for the least important.
Typing this code:
< h1 > Heading 1 < /h1 >
< h2 > Heading 1 < /h2 >
HTML LINES:
The < hr / > tag creates a horizontal line in an HTML page.
The hr element can be used to separate content:
Example
< pThis is a paragraph </p >
< hr / >
< pThis is a paragraph </p >
< hr / >
< pThis is a paragraph </p >
HTML PARAGRAPHS:
Paragraphs are defined with the < p >tag.
Example:
< p >This is a paragraph < /p >
HTML Line Breaks
Use the < br / > tag if you want a line break (a new line) without starting a new
paragraph:
Example
< p > This is < br / > a para < br / >graph with line breaks < /p >
HTML COLORS:
In HTML, colors can be added by using the style attribute. You can specify a color name (eg, blue), a hexadecimal value (eg, #0000ff), or an RGB value(egrgb(0,0,255)).Syntax
Foreground Color
To add color to an HTML element, you use style="color:{color}", where {color} is the color value. For example:
< h3 style="color:blue" >HTML Colors < /h3 >
Background Color
To add a colored border to an HTML element, you use style="border: {width} {color} {style}", where {width} is the width of the border, {color} is the color of the border, and {style} is the style of the border. For example:
< h3 style="border:1px blue solid;" > HTML Colors < /h3 >
Using Hexadecimal Value for Color
The most common methods for specifying colors are by using the color name or the hexadecimal value. Although color names are easier to remember, the hexadecimal values and RGB values provide you with more color options.
Hexadecimal values are a combination of letters and numbers. The numbers go from 0 - 9 and the letters go from A to F. When using hexadecimal color values in your HTML/CSS, you proceed the value with a hash (#). Different range of hexadecimal values for color you can get from your Photoshop tools, you don't have to memorize the color code.
You can make up your own colors by simply entering any six digit hexadecimal value (preceded by a hash). Check the following example , the only difference is that, instead of using "blue" as the value, we're using its hexadecimal equivalent (which is #0000ff):
< h3 style="color:#0000ff" >HTML Colors < /h3 >
HTML LINKS:
Links are found in nearly all Web pages. Links allow users to click their way from page to page.
HTML Hyperlinks (Links)
A hyperlink (or link) is a word, group of words, or image that you can click on to jump to a new document or a new section within the current document.
When you move the cursor over a link in a Web page, the arrow will turn into a little hand.
Links are specified in HTML using the tag.
The < a > tag can be used in two ways:
To create a link to another document, by using the href attribute
To create a bookmark inside a document, by using the name attribute
HTML Link Syntax
The HTML code for a link is simple. It looks like this:
< a href="url" > Link text < /a >
The href attribute specifies the destination of a link.
Example
< a href="http://www.ejobindia.com/" > Visit ejobindia < /a >
Clicking on this hyperlink will send the user to ejobindia' homepage.
Tip: The "Link text" doesn't have to be text. You can link from an image or any other HTML element.
HTML Links - The target Attribute
The target attribute specifies where to open the linked document.
The example below will open the linked document in a new browser window:
Example
< a href="http://www.ejobindia.com/" target="_blank" > Visit ejobindia! < /a >
HTML Links - The name Attribute
The name attribute specifies the name of an anchor.
The name attribute is used to create a bookmark inside an HTML document.
Bookmarks are not displayed in any special way. They are invisible to the reader.
Create a link to the "Useful Tips Section" inside the same document:
< a href="#tips" > Visit the Useful Tips Section < /a >
HTML IMAGES:
Images make up a large part of the web - most websites contain images. HTML makes it very easy for you to embed images into your web page.
To embed an image into a web page, the image first needs to exist in either .jpg, .gif, or .png format. You can create images in an image editor (such as Adobe Photoshop) and save them in the correct format.
Once you've created an image, you need to embed it into your web page. To embed the image into your web page, use the < img / > tag, specifying the actual location of the image.
HTML The < img > Tag and the Src Attribute
In HTML, images are defined with the < img > tag.
The < img > tag.tag is empty, which means that it contains attributes only, and has no closing tag.
To display an image on a page, you need to use the src attribute. Src stands for "source". The value of the src attribute is the URL of the image you want to display.
Syntax for defining an image:
< imgsrc="url" alt="some_text"/ >
The URL points to the location where the image is stored. An image named
" ejoblogo.jpg ", located in the "images" directory on " www.ejobindia.com " has the URL:
http://www.ejobindia.com/images/ejoblogo.jpg.
The browser displays the image where the < img > tag occurs in the document. If you put an image tag between two paragraphs, the browser shows the first paragraph, then the image, and then the second paragraph.
HTML The Alt Attribute
The required alt attribute specifies an alternate text for an image, if the image cannot be displayed.
The value of the alt attribute is an author-defined text:
< imgsrc= " http://www.ejobindia.com/images/ejoblogo.jpg " alt= " ejobindia " / >
The alt attribute provides alternative information for an image if a user for some reason cannot view it .
HTML TABLES:
In HTML, the original purpose of tables was to present tabular data. Although they are still used for this purpose today, many web designers tended to use tables for advanced layouts.
HTML Tables
Tables are defined with the < table > tag.
A table is divided into rows (with the < tr > tag), and each row is divided into data cells (with the < td > tag). td stands for "table data," and holds the content of a data cell. A < td > tag can contain text, links, images, lists, forms, other tables, etc.
Table Example
< table border="1" >
< tr >
< td >row 1, cell 1 < /td >
< td >row 1, cell 2 < /td >
< td >row 2, cell 1 < /td >
< td >row 2, cell 2 < /td >
< /tr >
< /table >
How the HTML code above looks in a browser:
HTML Tables and the Border Attribute
If you do not specify a border attribute, the table will be displayed without borders. Sometimes this can be useful, but most of the time, we want the borders to show. To display a table with borders, specify the border attribute:
< table border="1" >
< tr >
< td >Row 1, cell 1 < /td >
< td >Row 1, cell 2 < /td >
< /tr >
< /table >
Colspan
You can use the colspan attribute to make a cell span multiple columns.
HTML Code:
< table border="1" cellpadding="5" cellspacing="5" width="100%" >
< tr >
< th colspan="2" >Table header < /th >
< /tr >
< tr >
< td width="20%" > Table cell 1 < /td > < td >Table cell 2 < /td >
< /tr >
< /table >
Rowspan
Rowspan is for rows just what colspan is for columns (rowspan allows a cell to span multiple rows).
HTML Code:
< table border="1" cellpadding="5" cellspacing="5" width="100%">
< tr >
< th rowspan="2" > Table header < /th >< td > Table cell 1 < /td >
< /tr >
< tr >
< td >Table cell 2 < /td >
< /tr >
< /table >
HTML FORMS:
HTML enables us to create forms. This is where our websites can become more than just a nice advertising brochure. Forms allow us to build more dynamic websites that allow our users to interact with it.
HTML forms are used to pass data to a server.
A form can contain input elements like text fields, checkboxes, radio-buttons, submit buttons and more. A form can also contain select lists, textarea, fieldset, legend, and label elements.
The < form > tag is used to create an HTML form:
< form >
input elements
< /form >
HTML Forms - The Input Element
The most important form element is the input element.
The input element is used to select user information.
An input element can vary in many ways, depending on the type attribute. An input element can be of type text field, checkbox, password, radio button, submit button, and more.
The most used input types are described below.
Text Fields
< input type="text" /> defines a one-line input field that a user can enter text into:
< form >
First name: < input type="text" name="firstname" /> < br / >
Last name: < input type="text" name="lastname" / >
< /form >
How the HTML code above looks in a browser:
Note: The form itself is not visible. Also n\ACote that the default width of a text field is 20 characters.
Password Field
< input type="password" /> defines a password field:
<form >
Password: < input type="password" name="pwd" / >
< /form >
How the HTML code above looks in a browser:
Note: The characters in a password field are masked (shown as asterisks or circles).
Radio Buttons
< input type="radio" / > defines a radio button. Radio buttons let a user select ONLY ONE one of a limited number of choices:
< form >
< input type="radio" name="sex" value="male" /> Male <br />
< input type="radio" name="sex" value="female" /> Female
< /form >
How the HTML code above looks in a browser:
Checkboxes
<input type="checkbox" /> defines a checkbox. Checkboxes let a user select ONE or MORE options of a limited number of choices.
< form >
<input type="checkbox" name="vehicle" value="Bike" /> I have a bike < br / >
<input type="checkbox" name="vehicle" value="Car" /> I have a car
< /form >
How the HTML code above looks in a browser:
Submit Button
<input type="submit" /> defines a submit button.
A submit button is used to send form data to a server. The data is sent to the page specified in the form's action attribute. The file defined in the action attribute usually does something with the received input:
< form name="input" action="html_form_action.asp" method="get" >
Username: <input type="text" name="user" />
< input type="submit" value="Submit" />
< /form <
How the HTML code above looks in a browser:
If you type some characters in the text field above, and click the "Submit" button, the browser will send your input to a page called "html_form_action.asp". The page will show you the received input.
WHAT IS CSS?
CSS stands for Cascading Style Sheets.
CSS is a language that you can use to define styles against any HTML element.
Advantages of CSS
CSS saves time
When most of us first learn HTML, we get taught to set the font face, size, colour, style etc every time it occurs on a page. This means we find ourselves typing (or copying & pasting) the same thing over and over again. With CSS, you only have to specify these details once for any element. CSS will automatically apply the specified styles whenever that element occurs.you can change the appearance and layout of all the pages in your Web using External style sheets , just by editing one single CSS document! CSS allows developers to control the style and layout of multiple Web pages all at once so that it is a breakthrough in Web design . It is possible to define a style for each HTML element and apply it to as many Web pages as you want.To make a global change,all elements in the Web are updated automatically by simply changing the style.
Pages load faster
Less code means faster download times.
Easy maintenance
To change the style of an element, you only have to make an edit in one place.
Superior styles to HTML
CSS has a much wider array of attributes than HTML.
CSS SYNTAX
A style is a definition of fonts, colors, etc.
Each style has a unique name: a selector.
The selectors and their styles are defined in one place.
In your HTML contents you simply refer to the selectors whenever you want to activate a certain style.
Selectors are the names that you give to your different styles.
In the style definition you define how each selector should work (font, color etc.).
Then, in the body of your pages, you refer to these selectors to activate the styles.
For example:
<HTML>
<HEAD>
<style type="text/css">
B.headline {color:red; font-size:22px; font-family:arial; text-decoration:underline}
</style>
</HEAD>
<BODY>
<b>This is normal bold</b><br>
<b class="headline">This is headline style bold</b>
</BODY>
</HTML>
In this case B.headline is the selector.
The above example would result in this output:
There are three types of selectors:
HTML selectors
Used to define styles associated with HTML tags. (A way to redefine the look of tags)
Class selectors
Used to define styles that can be used without redefining plain HTML tags.
ID selectors
Used to define styles relating to objects with a unique ID (most often layers)
HTMLSelector {Property:Value;}
<HTML>
<HEAD>
<style type="text/css">
B {font-family:arial; font-size:14px; color:red}
</style>
</HEAD>
<BODY>
<b>This is a customized headline style bold</b>
</BODY>
</HTML>
.ClassSelector {Property:Value;}
<HTML>
<HEAD>
<style type="text/css">
.headline {font-family:arial; font-size:14px; color:red}
</style>
</HEAD>
<BODY>
<b class="headline">This is a bold tag carrying the headline class</b>
<br>
<i class="headline">This is an italics tag carrying the headline class</i>
</BODY>
</HTML>
Class selectors are used when you want to define a style that does not redefine an HTML tag entirely.
When referring to a Class selector you simply add the class to an HTML tag like in the above example (class="headline").
SPAN and DIV as carriers
Two tags are particularly useful in combination with class selectors: <SPAN> and<DIV>.
Both are "dummy" tags that don't do anything in themselves. Therefore, they are excellent for carrying CSS styles.
<SPAN> is an "inline-tag" in HTML, meaning that no line breaks are inserted before or after the use of it.
<DIV> is a "block tag", meaning that line breaks are automatically inserted to distance the block from the surrounding content (like <P> or <TABLE> tags).
<DIV> has a particular importance for layers. Since layers are separate blocks of information. <DIV> is an obvious choice when defining layers on your pages.
#IDSelector {Property:Value;}
<HTML>
<HEAD>
<style type="text/css">
#layer1 {position:absolute; left:100;top:100; z-Index:0}
#layer2 {position:absolute; left:140;top:140; z-Index:1}
</style>
</HEAD>
<BODY>
<div ID="layer1">
<table border="1" bgcolor="#FFCC00"><tr><td>THIS IS LAYER 1<br>POSITIONED AT 100,100</td></tr></table>
</div>
<div ID="layer2">
<table border="1" bgcolor="#00CCFF"><tr><td>THIS IS LAYER 2<br>POSITIONED AT 140,140</td></tr></table>
</div>
</BODY>
</HTML>
ID selectors are used when you want to define a style relating to an object with a unique ID.
This selector is most widely used with layers (as in the above example), since layers are always defined with a unique ID.
CSS can be defined for single tags ( inline ) by simply adding style="styledefinition:styleattribute;" to the tags.
Look at this example:
It is <b style="font-size:16px;">NOT</b> me.
CSS can be defined for entire pages by simply adding a style definition to the head section. (Internal)
Look at this example:
<html>
<head>
<title>MY CSS PAGE</title>
<style type="text/css">
.headlines, .sublines, infotext {font-face:arial; color:black; background:yellow; font-weight:bold;}
.headlines {font-size:14pt;}
.sublines {font-size:12pt;}
.infotext {font-size: 10pt;}
</style>
</head>
<body>
<span class="headlines">Welcome</span><br>
<div class="sublines">
This is an example page using CSS.<br>
The example is really simple,<br>
and doesn't even look good,<br>
but it shows the technique.
</div>
<table border="2"><tr><td class="sublines">
As you can see:<br>
The styles even work on tables.
</td></tr></table>
<hr>
<div class="infotext">
Example from EchoEcho.Com.
</div>
<hr>
</body>
</html>
In the above example, although we used the sublines style twice, we only had to define it once: in the <head>section.
By defining styles for entire pages, you will gain the freedom to easily change the styles even after the entire page has been made.
This is an obvious advantage for you as a designer. But the advantage is on the visitors side as well.
Since the styles are only defined in one place, the page size will be smaller, and thus faster to load.
There is a way to emphasize these advantages even more: using external CSS styles that work for entire sites.
SS can be defined for entire sites by simply writing the CSS definitions in a plain text file that is referred to from each of the pages in the site.
Rather than writing the entire CSS definition on each page, as in the previous examples, you can write it to a text file that is only loaded on the first page that a visitor sees at your site.
When the visitor jumps to other pages, the CSS text file will be cached and thus doesn't have to be transferred via the internet for subsequent pages.
This means that your pages will load faster while at the same time you will have extreme flexibility to change the style for your entire site even after it has been made.
Look at this example:
File: example.html
<link rel=stylesheet href="whatever.css" type="text/css">
</head>
<body>
<span class="headlines">Welcome</span><br>
<div class="sublines">
This is an example of a page using CSS.<br>
The example is really simple,<br>
and doesn't even look good,<br>
but it shows the technique.
</div>
<table border="2"><tr><td class="sublines">
As you can see:<br>
The styles even work on tables.
</td></tr></table>
<hr>
<div class="infotext">Example from EchoEcho.Com.</div>
<hr>
</body>
</html>
The above example is the exact same as we used for CSS defined for entire pages, with one important exception:
There is no style definition on the page. Instead we added a reference to an external style sheet:
<link rel=stylesheet href="whatever.css" type="text/css">
This means that the browser will look for a file called whatever.css and insert it at the place where the reference was found in the
html document.
So in order to complete our example we need to have a file called whatever.css that looks like this:
File: whatever.css
.headlines, .sublines, infotext {font-face:arial; color:black; background:yellow; font-weight:bold;}
.headlines {font-size:14pt;}
.sublines {font-size:12pt;}
.infotext {font-size: 10pt;}
Setting background colors
Background colors are defined similar to the colors mentioned above. For example you can set the background color of the entire page using the BODYselector:
BODY {background-color:#FF6666;}
Setting a background image
CSS lets you set a background image for both the page and single elements on the page.
In addition, CSS offers several positioning methods for background images.
You can define the background image for the page like this:
BODY {background-image:url(myimage.gif);}
You can control the repetition of the image with the background-repeatproperty.
background-repeat:repeat
Tiles the image until the entire page is filled, just like an ordinary background image in plain HTML.
background-repeat:repeat-x
Repeats the image horizontally - but not vertically.
background-repeat:repeat-y
Repeats the image vertically - but not horizontally.
background-repeat:no-repeat
Does not tile the image at all.
Positioning a background
Background positioning is done by entering a value for the left position and top position separated by a space.
In this example the image is positioned 75 pixels from the upper left corner of the page:
BODY {background-image:url(myimage.gif); background-position: 75px 75px;}
Note: Background positioning is not supported by Netscape 4 browsers.
Fixing a background
You can fixate an image at a certain position so that it doesn't move when scrolling occurs.
BODY {background-image:url(myimage.gif); background-attachment: fixed;}
Note: Background fixation is not supported by Netscape 4 browsers.
DEFINING STYLES FOR LINKS
As mentioned in the above table, there are four different selectors with respect to links.
You can specify whatever style you'd like to each of these selectors, just like you'd do with normal text.
A:link
Defines the style for normal unvisited links.
A:visited
Defines the style for visited links.
A:active
Defines the style for active links.
A link becomes active once you click on it.
A:hover
Defines the style for hovered links.
A link is hovered when the mouse moves over it.
Note: Not supported by Netscape browsers prior to version 6.
Example: Hover
<style type="text/css">
A:link {text-decoration: none}
A:visited {text-decoration: none}
A:active {text-decoration: none}
A:hover {text-decoration: underline; color: red;}
</style>
Another example would be to create links that are both underlined andoverlined.
Example: Underline/Overline
<style type="text/css">
A:link {text-decoration: none}
A:visited {text-decoration: none}
A:active {text-decoration: none}
A:hover {text-decoration: underline overline; color: red;}
</style>
With CSS, it is possible to work with layers: pieces of HTML that are placed on top of the regular page with pixel precision.
The advantages of this are obvious - but once again Netscape has very limited support of CSS layers - and to top it off: the limited support it offers is quite often executed with failures.
So the real challenge when working with layers is to make them work on Netscape browsers as well.
LAYER BASICS
LAYER 1 ON TOP:
<div style="position:relative; font-size:50px; z-index:2;">LAYER 1</div>
<div style="position:relative; top:-50; left:5; color:red; font-size:80px; z-index:1">LAYER 2</div>
LAYER 2 ON TOP:
<div style="position:relative; font-size:50px; z-index:3;">LAYER 1</div>
<div style="position:relative; top:-50; left:5; color:red; font-size:80px; z-index:4">LAYER 2</div>
To create a layer all you need to do is assign the position attribute to your style. The position can be either absolute or relative.
The position itself is defined with the top and left properties.
Finally, which layer is on top is defined with the z-index attribute.
RELATIVE VERSUS ABSOLUTE POSITIONING
You can either position your layer calculated from the upper left corner(absolute) or calculated from the position where the layer itself is inserted (relative).
position:absolute
If you define the position to be absolute it will be calculated from the upper left corner of the page - unless the layer is defined inside another layer, in which case it will be calculated from the upper left corner of the parent layer.
position:relative
If you define the position to be relative it will be relative to the position of the tag that carries the style.
That is, if you add a relatively positioned layer in the middle of the page, then the position will be calculated from that exact spot in the middle of your page where it was added.
Valid values for the visibility property are: visible and hidden.
This example shows how to create an invisible layer:
<div style="position:relative; visibility:hidden;">HELLO!!!</div>
JAVASCRIPT:
Javascript is a scripting language that will allow you to add real programming to your webpages.
You can create small application type processes with javascript, like a calculator or a primitive game of some sort.
However, there are more serious uses for javascript:
Browser Detection
Detecting the browser used by a visitor at your page. Depending on the browser, another page specifically designed for that browser can then be loaded.
Cookies
Storing information on the visitor's computer, then retrieving this information automatically next time the user visits your page. This technique is called "cookies".
Control Browsers
Opening pages in customized windows, where you specify if the browser's buttons, menu line, status line or whatever should be present.
Validate Forms
Validating inputs to fields before submitting a form.
An example would be validating the entered email address to see if it has an @ in it, since if not, it's not a valid address.
Since javascript isn't HTML, you will need to let the browser know in advance when you enter javascript to an HTML page. This is done using the <script> tag.
The browser will use the <script> type="text/javascript"> and </script> to tell where javascript starts and ends.
Knowing that javascript needs to be entered between <script> tags, is a start. But there are a few other things you need to know before writing your first javascript:
Javascript lines end with a semicolon.
You may have noticed from the example on the previous page that javascript lines end with a semicolon.
You can easily put all your javascript on a single line without destroying the performance of it.
However, you would destroy the overview of your script so it is not advisable.
Always put the text within " ".
When entering text to be handled by javascript, you should always put the text within " ".
If you forget to enclose your text in " ", javascript will interpret your text as being variables rather than text.
In the next section you will learn why this would cause an error to your script.
Capital letters are different from lowercase letters.
You should always remember that capital letters are different from lowercase letters.
This means that when you write commands in javascript, you need to type capital letters in the correct places, and nowhere else.
Incorrect capitalization is probably the most common source of error for javascript programmers on all levels!!
Events are actions that can be detected by javascript.
An example would be the onmouseover event, which is detected when the user moves the mouse over an object.
Another event is the onload event, which is detected as soon as the page is finished loading.
Usually, events are used in combination with functions, so that the function does not start until the event happens.
The function simply shifts two images. One image that shows the button in an "up" position, and another image that shows the button in a "down" position.
If this function is called using an onmouseover event, it will make it look as if the button is pressed down when the mouse is moved over the image.
The following are the most important events recognized by javascript:
Events are used for two main purposes:
To perform a function upon detection of the event,
To show a popup box upon detection of the event.
onFocus, onblur and onchange are mainly used in combination with validation of form fields.
Lets say you had a function called validateEmail() that would check to see if an entered email address has an @ in it, and if it has a meaningful end, such as "com", "net" or whatever. Furthermore, suppose the user could enter his email address in a form.
You would then use the onchange event to call the function whenever the user changes the content of the field:
<input type="text" size="20" onchange="validateEmail()">;
onload and onunload are mainly used for popups that appear when the user enters or leaves the page.
Another important use is in combination with cookies that should be set upon arrival or leaving your pages.
For example, you might have a popup asking the user to enter his name upon his first arrival to your page. The name is then stored in a cookie. Furthermore, when the visitor leaves your page a cookie stores the current date.
Next time the visitor arrives at your page, it will have another popup saying something like: "Welcome Bill Clinton, this page has not been updated since your last visit 8 days ago".
Another common use of the onLoad and onunload events is: Some annoying pages have a function that immediately opens several other windows as soon as you enter the page. This is a clear break of netiquette, and is not considered proper webdesign.
onsubmit is used for one major purpose: To validate all fields within a form before actually submitting it.
In the above example for onchange we showed how you can validate a single form field.
Sometimes however, the visitor might find it annoying to have validations in the middle of entering fields on a form. Rather than validating after each input, you might want the form to be validated only upon clicking the submit button.
This can be done using the onsubmit event.
Assume you made a function named checkform() that would validate entries to a form.
Now you want this function to be called when the user clicks the submit button.
If the content is not accepted by your function the submit should be cancelled.
This way nothing would be submitted unless your function accepted the content.
What you should do, is: add an onsubmit event to the <form> tag this way:
<form method="yourchoice" action="yourchoice" onsubmit="return checkform()">
The function checkform() returns either true or false.
If it returns true the submit will take place.
If it returns false the submit will be cancelled.
onmouseover and onmouseout are mainly used for one purpose: To create animated buttons.
You may have noticed that these events can only be used in combination with the link tag <a>.
JavaScript Syntax : A JavaScript consists of JavaScript statements that are placed within the <script>... </script> HTML tags in a web page. You can place the <script> tag containing your JavaScript anywhere within you web page but it is preferred way to keep it within the <head> tags.
<script ...>
JavaScript code
</script>
Variables: Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword.
DIALOG BOX IN JAVASCRIPT :
JavaScript supports three important types of dialog boxes. These dialog boxes can be used to raise and alert, or to get confirmation on any input or to have a kind of input from the users.
Alert Dialog Box :
An alert dialog box is mostly used to give a warning message to the users. Like if one input field is required to enter some text but the user does not enter that field then as a part of validation you can use an alert box to give a warning message.. Alert box gives only one button "OK" to select and proceed.
<head>
<script type="text/javascript">
alert("Warning Message");
</script>
</head>
Confirmation Dialog Box:
A confirmation dialog box is mostly used to take user's consent on any option. It displays a dialog box with two buttons: OK and Cancel.If the user clicks on the OK button the window method confirm() will return true. If the user clicks on the Cancel button confirm() returns false.
<head>
<script>
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
alert("User wants to continue!");
return true;
}else{
alert("User does not want to continue!");
return false;
}
</script>
</head>
Prompt Dialog Box:
The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus it enables you to interact with the user. The user needs to fill in the field and then click OK.. This dialog box with two buttons: OK and Cancel. If the user clicks on the OK button the window method prompt() will return the entered value from the text box. If the user clicks on the Cancel button the window method prompt() returns null.
<head>
<script type="text/javascript">
var retVal = prompt("Enter your name : ", "your name here");
alert("You have entered : " + retVal );
</script>
</head
OPERATORS :
Comparison and Logical operators are used to test for true or false.
Comparison Operators :
Comparison operators are used in logical statements to determine equality or difference between variables or values.
Operator Description
== is equal to
=== is exactly equal to (value and type)
!= is not equal
> is greater than
< is less than
>= is greater than or equal to
<= is less than or equal to
Logical Operators :
Logical operators are used in determine the logic between variables or values.
Operator Description
&& and
|| or
! not
Conditional Statements
Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
if statement - use this statement if you want to execute some code only if a specified condition is true
if...else statement - use this statement if you want to execute some code if the condition is true and another code if the condition is false
if...else if....else statement - use this statement if you want to select one of many blocks of code to be executed
switch statement - use this statement if you want to select one of many blocks of code to be executed
Example
<html>
<head>
<title>Untitled Document</title>
<script type="text/javascript">
//If the time is less than 10, you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.
var d = new Date();
var time = d.getHours();
if (time < 10)
{
document.write("Good morning!");
}
else
{
document.write("Good day!");
}
</script>
</head>
<body>
</body>
</html>
JAVASCRIPT LOOPS :
Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this. In JavaScript, there are two different kind of loops:
for - loops through a block of code a specified number of times
while - loops through a block of code while a specified condition is true
The for Loop :
The for loop is used when you know in advance how many times the script should run.
Syntax
for (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}
Example
The example below defines a loop that starts with i=0. The loop will continue to run as long as it is less than, or equal to 5. i will increase by 1 each time the loop runs.
Note: The increment parameter could also be negative, and the <= could be any comparing statement.
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
While Loop :
The while loop loops through a block of code while a specified condition is true.
Syntax
while (var<=endvalue)
{
code to be executed
}
Note: The <= could be any comparing operator.
Example
The example below defines a loop that starts with i=0. The loop will continue to run as long as it is less than, or equal to 5. i will increase by 1 each time the loop runs:
<html>
<body>
<script type="text/javascript">
var i=0;
while (i<=5)
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
</script>
</body>
</html>
JAVASCRIPT - FORM VALIDATION :
Form validation used to occur at the server, after the client had entered all necessary data and then pressed the Submit button. JavaScript, provides a way to validate form's data on the client's computer before sending it to the web server.
Form Validation code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function valid()
{
var n=document.f1.user.value;
if(n=='')
{
alert("Please Enter Username");
return false;
}
if(!isNaN(n))
{
alert("Please Enter your user name in text");
return false;
}
var a,b,c,d;
a=document.f1.pwd.value;
if(a=='')
{
alert("Please enter your password");
return false;
}
b=document.f1.pwd1.value;
if(b=='')
{
alert("Please Enter Confirm Password Field")
return false;
}
if(!(a==b))
{
alert("Please Enter same password in both the fields");
return false;
}
c=document.f1.gen[0].checked;
d=document.f1.gen[1].checked;
if(!c && !d)
{
alert("Please Enter Gender");
return false;
}
var f=document.f1.farea.value;
if(f=="Please Select")
{
alert('Please Select a functional Area');
return false;
}
var p=document.f1.no.value;
if(p=='')
{
alert("Please enter Phone Number");
return false;
}
if(isNaN(p))
{
alert("No Character in Phone area");
return false;
}
if(p.length<10)
{
alert("Please enter A valid phone number");
return false;
}
if(p.charAt(0)!=9 && p.charAt(0)!=0 && p.charAt(0)!=2)
{
alert("Please Start With 9,0 or 2");
return false;
}
var x=document.f1.email.value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Form with JavaScript</title>
</head>
<body>
<form method="post" action="submit.php" name="f1" onsubmit="return valid();">
<table border="2" align="center">
<tr><th><label>Username</label></th><td><input type="text" name="user" /></td></tr>
<tr><th><label>Password</label></th><td><input type="password" name="pwd" /></td></tr>
<tr><th><label>Confirm Password</label></th><td><input type="password" name="pwd1" /></td></tr>
<tr><th><label>PhoneNo.</label></th><td><input type="text" name="no" /></td></tr>
<tr><th><label>Gender</label></th><td><input type="radio" name="gen" value="male" />Male
<input type="radio" name="gen" value="female" />Female</td></tr>
<tr><th><label>Email</label></th><td><input type="text" name="email" /></td></tr>
<tr><th><label>Functional Area</label></th><td><select name="farea">
<option>Please Select</option>
<?php
$a=array('BPO','Web Developer','Networking','S/Developer','Hardware');
for($i=0;$i<5;$i++)
{
echo "<option>".$a[$i]."</option>";
}
?></select></td></tr>
<tr><th></th><td><input type="submit" name="submit" value="SUBMIT" /></td></tr></table></form>
<?php
echo $_REQUEST['n'];
?>
</body>
</html>
CODE FOR DIGITAL CLOCK USING SETTIMEOUT() :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout('startTime()',500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
</script>
</head>
<body onLoad="startTime()">
<div id="txt"></div>
</body>
</html>
SUBMITTING A FORM WITHOUT USING SUBMIT BUTTON :
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" language="javascript">
function submitform(){
document.form.submit();
}
</script>
<title>Form Submit</title>
</head>
<body>
<form action="form.php" method="post" name="form" onsubmit="return valid()">
<a href="javascript:submitform()" onclick="return valid()">Go</a>
</body>
</html>
JQUERY :
jQuery is a fast and concise JavaScript library created by John Resig in 2006.
jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for Rapid Web Development.
What is jQuery ?
jQuery is a fast and concise JavaScript Library created by John Resig in 2006 with a nice motto: Write less, do more.
jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.
jQuery is a JavaScript toolkit designed to simplify various tasks by writing less code. Here is the list of important core features supported by jQuery:
DOM manipulation: The jQuery made it easy to select DOM elements, traverse them and modify their content by using a cross-browser open source selector engine called Sizzle.
Event handling: The jQuery offers an elegant way to capture a wide variety of events, such as a user clicking on a link, without the need to clutter the HTML code itself with event handlers.
AJAX Support: The jQuery helps you a lot to develop a responsive and feature-rich site using AJAX technology.
Animations: The jQuery comes with plenty of built-in animation effects which you can use in your websites.
Lightweight: The jQuery is very lightweight library - about 19KB in size ( Minified and gzipped ).
Cross Browser Support: The jQuery has cross-browser support, and works well in IE 6.0+, FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+
Latest Technology: The jQuery supports CSS3 selectors and basic XPath syntax.
How to install jQuery ?
This is very simple to do and requires setup to use jQuery library. You have to carry two simple steps:
Go to the download page to grab the latest version available.
Now put downloaded jquery-1.3.2.min.js file in a directory of your website, e.g. /jquery.
The downloaded file name jquery-1.3.2.min.js may vary for your version. Your minified version would be kind of unreadable which would not have any new line or unnecessary words in it.
jQuery does not require any special installation and is very similar to JavaScript, we do not need any compilation or build phase to use jQuery.
JQUERY DETAILS:
This is an optional technique that many developers are using today. Instead of hosting the jQuery source code on your own server, you can link to it remotely. This ensures the fastest possible download time of the source code, since many users visiting your site might have the file already cached in their browser. Here is how your <script> tag should look:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js?ver=1.4.0"></script>
The first thing you need to be up and running with jQuery is what’s called the “document ready” handler. Pretty much everything you code in jQuery will be contained inside one of these. This accomplishes two things: First, it ensures that the code does not run until the DOM is ready. This confirms that any elements being accessed are actually in existence, so the script won’t return any errors. Second, this ensures that your code is unobtrusive. That is, it’s separated from content (HTML) and presentation (CSS).
Here is what it looks like:
$(document).ready(function() {
// all jQuery code goes here
});
Although you will normally include your jQuery code inside the above handler, for brevity the rest of the code examples in this tutorial will not include the “ready” handler.
The jQuery library allows you to select elements in your HTML by wrapping them in $("")(you could also use single quotes), which is the jQuery wrapper. Here are some examples of “wrapped sets” in jQuery:
$("div"); // selects all HTML div elements
$("#myElement"); // selects one HTML element with ID "myElement"
$(".myClass"); // selects HTML elements with class "myClass"
$("p#myElement"); // selects paragraph elements with ID "myElement"
$("ul li a.navigation"); // selects anchors with class "navigation" that are nested in list items
$("p > a"); // selects anchors that are direct children of paragraphs
$("input[type=text]"); // selects inputs that have specified type
$("a:first"); // selects the first anchor on the page
$("p:odd"); // selects all odd numbered paragraphs
$("li:first-child"); // every list item that's first child in a list
$(":animated"); // selects elements currently being animated
$(":button"); // selects any button elements (inputs or buttons)
$(":radio"); // selects radio buttons
$(":checkbox"); // selects checkboxes
$(":checked"); // selects selected checkboxes or radio buttons
$(":header"); // selects header elements (h1, h2, h3, etc.)
CSS styles can be added to elements easily using jQuery, and it’s done in a cross-browser fashion. Here are some examples to demonstrate this: ?
$("p").css("width", "400px"); // adds a width to all paragraphs
$("#myElement").css("color", "blue") // makes text color blue on element #myElement
$("ul").css("border", "solid 1px #ccc") // adds a border to all lists
There are a number of ways to manipulate groups of elements with jQuery, including manipulating the content of those elements (whether text, inline elements, etc).Get the HTML of any element (similar to innerHTML in JavaScript):
var myElementHTML = $("#myElement").html(); // variable contains all HTML (including text) inside #myElement
Specific event handlers can be established using the following code:
$("a").click(function() {
// do something here
// when any anchor is clicked
});
The code inside function() will only run when an anchor is clicked. Some other common events you might use in jQuery include:
blur, focus, hover, keydown, load, mousemove, resize, scroll, submit, select.
The syntax for showing, hiding an element (or toggling show/hide) is:
$("#myElement").hide("slow", function() {
// do something once the element is hidden
}
$("#myElement").show("fast", function() {
// do something once the element is shown
}
$("#myElement").toggle(1000, function() {
// do something once the element is shown/hidden
}
Remember that the “toggle” command will change whatever state the element currently has, and the parameters are both optional. The first parameter indicates the speed of the showing/hiding. If no speed is set, it will occur instantly, with no animation. A number for “speed” represents the speed in milliseconds. The second parameter is an optional function that will run when the command is finished executing.You can also specifically choose to fade an element in or out, which is always done by animation:
$("#myElement").fadeOut("slow", function() {
// do something when fade out finished
}
$("#myElement").fadeIn("fast", function() {
// do something when fade in finished
}
To fade an element only partially, either in or out:
$("#myElement").fadeTo(2000, 0.4, function() {
// do something when fade is finished
}
The second parameter (0.4) represents “opacity”, and is similar to the way opacity is set in CSS. Whatever the opacity is to start with, it will animate (fadeTo) until it reaches the setting specified, at the speed set (2000 milliseconds). The optional function (called a “callback function”) will run when the opacity change is complete. This is the way virtually all callback functions in jQuery work.
You can slide elements, animate elements, and even stop animations in mid-sequence. To slide elements up or down:
$("#myElement").slideDown("fast", function() {
// do something when slide down is finished
}
$("#myElement").slideUp("slow", function() {
// do something when slide up is finished
}
$("#myElement").slideToggle(1000, function() {
// do something when slide up/down is finished
}
To animate an element, you do so by telling jQuery the CSS styles that the item should change to. jQuery will set the new styles, but instead of setting them instantly (as CSS or raw JavaScript would do), it does so gradually, animating the effect at the chosen speed:
$("#myElement").animate(
{
opacity: .3,
width: "500px",
height: "700px"
}, 2000, function() {
// optional callback after animation completes
}
);
JQUERY AJAX:
AJAX is the art of exchanging data with a server, and update parts of a web page - without reloading the whole page.
The following table lists all the jQuery AJAX methods:
$.ajax() method:
$.ajax() returns the XMLHttpRequest that it creates. In most cases you won't need that object to manipulate directly, but it is available if you need to abort the request manually.
Following is a simple example a simple showing the usage of this method. Here we make use of success handler to populate returned HTML −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#driver").click(function(event){
$.ajax( {
url:'result.html',
success:function(data) {
$('#stage').html(data);
}
});
});
});
</script>
</head>
<body>
<p>Click on the button to load result.html file:</p>
<div id = "stage" style = "background-color:blue;">
STAGE
</div>
<input type = "button" id = "driver" value = "Load Data" />
</body>
</html>
$.get() method :
This method gets the target data and results the data if it’s successfully fetched
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("http://localhost/JQ_AJAX/demo.txt", function(data, status){
alert(status);
$("#show").html(data);
});
});
});
</script>
</head>
<body>
<button>AJAX GET</button>
<p id="show"></p>
</body>
</html>
$.post() method :
This method post/send the data on a target file
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<center>
<h1>AJAX program using post method</h1>
Enter username: <input type="text" id="username"><br><br>
Enter location: <input type="text" id="location">
<button id="btnclick" >Click me</button>
<p id="loaddata"></p>
</center>
<!-- onclick="fun()" -->
<script type="text/javascript">
$(document).ready(function(){
$("#btnclick").click(function(){
var user=$("#username").val();
var loc=$("#location").val();
$.post('http://localhost/JQ_AJAX/load.php',
{username : user,
location : loc},
function(data,status){
$("#loaddata").html(data);
alert(status);
});
});
});
</script></body>
</html>
JSON (JavaScript Object Notation)
JSON is a syntax for storing and exchanging data.
JSON is text, written with JavaScript object notation.
Exchanging Data
When exchanging data between a browser and a server, the data can only be text.
JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server.
We can also convert any JSON received from the server into JavaScript objects.
This way we can work with the data as JavaScript objects, with no complicated parsing and translations.
Sending Data
If you have data stored in a JavaScript object, you can convert the object into JSON, and send it to a server:
Example
var myObj = {name: "John", age: 31, city: "New York"};
var myJSON = JSON.stringify(myObj);
window.location = "demo_json.php?x=" + myJSON;
Receiving Data
If you receive data in JSON format, you can convert it into a JavaScript object:
Example
var myJSON = '{"name":"John", "age":31, "city":"New York"}';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;
JSON Objects
Example
{ "name":"John", "age":30, "car":null }
JSON objects are surrounded by curly braces {}.
JSON objects are written in key/value pairs.
Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null).
Keys and values are separated by a colon.
Each key/value pair is separated by a comma.
Accessing Object Values
You can access the object values by using dot (.) notation:
Example
myObj = { "name":"John", "age":30, "car":null };
x = myObj.name;
You can also access the object values by using bracket ([]) notation:
Example
myObj = { "name":"John", "age":30, "car":null };
x = myObj["name"];
Looping an Object
You can loop through object properties by using the for-in loop:
myObj = { "name":"John", "age":30, "car":null };
for (x in myObj) {
document.getElementById("demo").innerHTML += x;
}
In a for-in loop, use the bracket notation to access the property values:
Example
myObj = { "name":"John", "age":30, "car":null };
for (x in myObj) {
document.getElementById("demo").innerHTML += myObj[x];
}
Nested JSON Objects
Values in a JSON object can be another JSON object.
myObj = {
"name":"John",
"age":30,
"cars": {
"car1":"Ford",
"car2":"BMW",
"car3":"Fiat"
}
}
You can access nested JSON objects by using the dot notation or bracket notation:
x = myObj.cars.car2;
// or:
x = myObj.cars["car2"];
Modify Values
You can use the dot notation to modify any value in a JSON object:
myObj.cars.car2 = "Mercedes";
You can also use the bracket notation to modify a value in a JSON object:
myObj.cars["car2"] = "Mercedes";
Delete Object Properties
Use the delete keyword to delete properties from a JSON object:
delete myObj.cars.car2;
JSON.parse()
A common use of JSON is to exchange data to/from a web server.
When receiving data from a web server, the data is always a string.
Parse the data with JSON.parse(), and the data becomes a JavaScript object.
Example - Parsing JSON
Imagine we received this text from a web server:
'{ "name":"John", "age":30, "city":"New York"}'
Use the JavaScript function JSON.parse() to convert text into a JavaScript object:
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
Use the JavaScript object in your page:
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
</script>
JSON.stringify()
A common use of JSON is to exchange data to/from a web server.
When sending data to a web server, the data has to be a string.
Convert a JavaScript object into a string with JSON.stringify().
Stringify a JavaScript Object
Imagine we have this object in JavaScript:
var obj = { name: "John", age: 30, city: "New York" };
Use the JavaScript function JSON.stringify() to convert it into a string.
var myJSON = JSON.stringify(obj);
myJSON is now a string, and ready to be sent to a server:
Example
var obj = { name: "John", age: 30, city: "New York" };
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
Stringify a JavaScript Array
It is also possible to stringify JavaScript arrays:
Imagine we have this array in JavaScript:
var arr = [ "John", "Peter", "Sally", "Jane" ];
Use the JavaScript function JSON.stringify() to convert it into a string.
var myJSON = JSON.stringify(arr);
The result will be a string following the JSON notation.
myJSON is now a string, and ready to be sent to a server:
Example
var arr = [ "John", "Peter", "Sally", "Jane" ];
var myJSON = JSON.stringify(arr);
document.getElementById("demo").innerHTML = myJSON;
JavaScript - HTML DOM Methods
HTML DOM methods are actions you can perform (on HTML Elements).
HTML DOM properties are values (of HTML Elements) that you can set or change.
The HTML DOM can be accessed with JavaScript (and with other programming languages).
In the DOM, all HTML elements are defined as objects.
The programming interface is the properties and methods of each object.
A property is a value that you can get or set (like changing the content of an HTML element).
A method is an action you can do (like add or deleting an HTML element).
The following example changes the content (the innerHTML) of the <p> element with id="demo":
Example
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
In the example above, getElementById is a method, while innerHTML is a property.
The getElementById Method
The most common way to access an HTML element is to use the id of the element.
In the example above the getElementById method used id="demo" to find the element.
The innerHTML Property
The easiest way to get the content of an element is by using the innerHTML property.
The innerHTML property is useful for getting or replacing the content of HTML elements.
Document Object
The HTML DOM document object is the owner of all other objects in your web page.
The document object represents your web page.
If you want to access any element in an HTML page, you always start with accessing the document object.
Below are some examples of how you can use the document object to access and manipulate HTML.
EventListener
addEventListener() method
The addEventListener() method attaches an event handler to the specified element.
The addEventListener() method attaches an event handler to an element without overwriting existing event handlers.
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method to attach a click event to a button.</p>
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
document.getElementById("myBtn").addEventListener("click", displayDate);
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
</body>
</html>
Nodes
In the DOM, all parts of the document, such as elements, attributes, text, etc. are organized in a hierarchical tree-like structure; similar to a family tree in real life that consists of parents and children. In DOM terminology these individual parts of the document are known as nodes.
To understand this more clearly, let's consider the following simple HTML document:
Example
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Mobile OS</h1>
<ul>
<li>Android</li>
<li>iOS</li>
</ul>
</body>
</html>
The above HTML document can be represented by the following DOM tree:
The above diagram demonstrates the parent/child relationships between the nodes. The topmost node i.e. the Document node is the root node of the DOM tree, which has one child, the <html> element. Whereas, the <head> and <body> elements are the child nodes of the <html> parent node.
The <head> and <body> elements are also siblings since they are at the same level. Further, the text content inside an element is a child node of the parent element. So, for example, "Mobile OS" is considered as a child node of the <h1> that contains it, and so on.
Creating New HTML Elements (Nodes)
To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
</script>
This code creates a new <p> element:
var para = document.createElement("p");
To add text to the <p> element, you must create a text node first. This code creates a text node:
var node = document.createTextNode("This is a new paragraph.");
Then you must append the text node to the <p> element:
para.appendChild(node);
Finally you must append the new element to an existing element.
This code finds an existing element:
var element = document.getElementById("div1");
This code appends the new element to the existing element:
element.appendChild(para);
Collection
An HTMLCollection is a list of nodes. An individual node may be accessed by either ordinal index or the node's name or id attributes. Note: Collections in the HTML DOM are assumed to be live meaning that they are automatically updated when the underlying document is changed.
HTMLCollection Length
The length property defines the number of elements in an HTMLCollection:
Example
var myCollection = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = myCollection.length;
Create a collection of all <p> elements
Display the length of the collection
The length property is useful when you want to loop through the elements in a collection:
Example
Change the background color of all <p> elements:
var myCollection = document.getElementsByTagName("p");
var i;
for (i = 0; i < myCollection.length; i++) {
myCollection[i].style.color = "red";
}
HTMLCollection Object
The getElementsByTagName() method returns an HTMLCollection object.
An HTMLCollection object is an array-like list (collection) of HTML elements.
The following code selects all <p> elements in a document:
Example
var x = document.getElementsByTagName("p");
The elements in the collection can be accessed by an index number.
To access the second <p> element you can write:
y = x[1];
NodeList
The NodeList object specifies the abstraction of an ordered collection of nodes. The items in the NodeList are accessible via an integral index, starting from 0.
Attributes
The following table lists the attributes of the NodeList object −
Methods
The following is the only method of the NodeList object.
All browsers return a NodeList object for the property childNodes.
Most browsers return a NodeList object for the method querySelectorAll().
The following code selects all <p> nodes in a document:
var myNodeList = document.querySelectorAll("p");
The elements in the NodeList can be accessed by an index number.
To access the second <p> node you can write:
y = myNodeList[1];
The length property defines the number of nodes in a node list:
var myNodelist = document.querySelectorAll("p");
document.getElementById("demo").innerHTML = myNodelist.length;
JavaScript “var” and “let”
var and let are both used for variable declaration in javascript but the difference between them is that var is function scoped and let is block scoped.
It can be said that a variable declared with var is defined throughout the program as compared to let.
Example : var
function func() {
// x is known here but not defined.
console.log('value of x here: ', x)
{
var x = 10;
x = x + 5;
}
// x is still known here and has a value.
console.log('value of x after for block: ', x)
}
// x is NOT known here.
func()
Example : let
function func() {
// x is NOT known here. Try uncommenting the line below.
// console.log('value of x here: ', x)
{
let x = 10;
x = x + 5;
}
// x is NOT known here. Try uncommenting the line below.
// console.log('value of x after for block: ', x)
}
// x is NOT known here.
func()
JavaScript “const”
A variable is a data structure that contains information that is expected to change. A constant is a data structure that contains information that will never change. If there is room for error, var should always be used. However, not all information that never changes in the lifetime of a program needs to be declared with const. If under different circumstances the information should change, use var to indicate that, even if the actual change doesn't appear in your code.
If we assign a primitive value to a constant, we cannot change the primitive value:
Example
const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error
Constant Objects can Change
You can change the properties of a constant object:
Example
// You can create a const object:
const car = {type:"Fiat", model:"500", color:"white"};
// You can change a property:
car.color = "red";
// You can add a property:
car.owner = "Johnson";
But you can NOT reassign a constant object:
Example
const car = {type:"Fiat", model:"500", color:"white"};
car = {type:"Volvo", model:"EX60", color:"red"}; // ERROR
Arrow functions
There’s another very simple and concise syntax for creating functions, that’s often better than Function Expressions.
It’s called “arrow functions”, because it looks like this:
let func = (arg1, arg2, ...argN) => expression
…This creates a function func that accepts arguments arg1..argN, then evaluates the expression on the right side with their use and returns its result.
In other words, it’s the shorter version of:
let func = function(arg1, arg2, ...argN) {
return expression;
};
Let’s see a concrete example:
let sum = (a, b) => a + b;
/* This arrow function is a shorter form of:
let sum = function(a, b) {
return a + b;
};
*/
alert( sum(1, 2) ); // 3
As you can, see (a, b) => a + b means a function that accepts two arguments named a and b. Upon the execution, it evaluates the expression a + b and returns the result.
If we have only one argument, then parentheses around parameters can be omitted, making that even shorter.
For example:
let double = n => n * 2;
// roughly the same as: let double = function(n) { return n * 2 }
alert( double(3) ); // 6
If there are no arguments, parentheses will be empty (but they should be present):
let sayHi = () => alert("Hello!");
sayHi();
Arrow functions can be used in the same way as Function Expressions.
For instance, to dynamically create a function:
let age = prompt("What is your age?", 18);
let welcome = (age < 18) ?
() => alert('Hello') :
() => alert("Greetings!");
welcome();
Arrow functions may appear unfamiliar and not very readable at first, but that quickly changes as the eyes get used to the structure.
They are very convenient for simple one-line actions, when we’re just too lazy to write many words.
Multiline arrow functions
The examples above took arguments from the left of => and evaluated the right-side expression with them.
Sometimes we need something a little bit more complex, like multiple expressions or statements. It is also possible, but we should enclose them in curly braces. Then use a normal return within them.
Like this:
let sum = (a, b) => { // the curly brace opens a multiline function
let result = a + b;
return result; // if we use curly braces, then we need an explicit "return"
};
alert( sum(1, 2) ); // 3
More to come
Here we praised arrow functions for brevity. But that’s not all!
Arrow functions have other interesting features.
To study them in-depth, we first need to get to know some other aspects of JavaScript, so we’ll return to arrow functions later in the chapter Arrow functions revisited.
For now, we can already use arrow functions for one-line actions and callbacks.
Summary
Arrow functions are handy for one-liners. They come in two flavors:
Without curly braces: (...args) => expression – the right side is an expression: the function evaluates it and returns the result.
With curly braces: (...args) => { body } – brackets allow us to write multiple statements inside the function, but we need an explicit return to return something.
JavaScript Classes
A class is a type of function, but instead of using the keyword function to initiate it, we use the keyword class, and the properties are assigned inside a constructor() method.
class Car {
constructor(brand) {
this.carname = brand;
}
present() {
return "I have a " + this.carname;
}
}
mycar = new Car("Ford");
document.getElementById("demo").innerHTML = mycar.present();
Sending parameter
class Car {
constructor(brand) {
this.carname = brand;
}
present(x) {
return x + ", I have a " + this.carname;
}
}
mycar = new Car("Ford");
document.getElementById("demo").innerHTML = mycar.present("Hello");
Filter
The filter() method creates an array filled with all array elements that pass a test (provided as a function).
Note: filter() does not execute the function for array elements without values.
Note: filter() does not change the original array.
Example
Return an array of all the values in the ages array that are 18 or over:
var ages = [32, 33, 16, 40];
function checkAdult(age) {
return age >= 18;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.filter(checkAdult);
}
Example
Return an array of all the values in the ages array that are a specific number or over:
<p>Minimum age: <input type="number" id="ageToCheck" value="18"></p>
<button onclick="myFunction()">Try it</button>
<p>All ages above minimum: <span id="demo"></span></p>
<script>
var ages = [32, 33, 12, 40];
function checkAdult(age) {
return age >= document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.filter(checkAdult);
}
</script>
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
MODULE 2
React JS overview, Basic configuration & installation
React JS overview
Definition
ReactJS is a declarative, efficient, and flexible JavaScript library for building reusable UI components. It is an open-source, component-based front end library which is responsible only for the view layer of the application.
Features of React
JSX − JSX is JavaScript syntax extension. It isn't necessary to use JSX in React development, but it is recommended.
Components − React is all about components. You need to think of everything as a component. This will help you maintain the code when working on larger scale projects.
Unidirectional data flow and Flux − React implements one-way data flow which makes it easy to reason about your app. Flux is a pattern that helps keeping your data unidirectional.
React Advantages
Uses virtual DOM which is a JavaScript object. This will improve apps performance, since JavaScript virtual DOM is faster than the regular DOM.
Can be used on client and server side as well as with other frameworks.
Components and data patterns improve readability, which helps to maintain larger apps.
Basic configuration & installation
You’ll need to have Node >= 8.10 on your local development machine.
Open the command and select the path where you want to install react.
npx create-react-app my-app
cd my-app
npm start
Webpack is a command line tool to create bundles of assets (code and files). Webpack doesn't run on the server or the browser. Webpack takes all your javascript files and any other assets and transforms then into one huge file. This big file can then be sent by the server to a client's browser.
What is Babel?
Babel is a JavaScript compiler
Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments. Here are the main things Babel can do for you:
Transform syntax
Polyfill features that are missing in your target environment (through @babel/polyfill)
Source code transformations (codemods)
And more! (check out these videos for inspiration)
Why react is a library not a framework?
React is a library for building composable user interfaces. It encourages the creation of reusable UI components which present data that changes over time. It is not a complete application framework like angular, it is just a view layer. So it is not directly comparable to frameworks like angular.
DOM
Just to get things straight - DOM stands for Document Object Model and is an abstraction of a structured text. For web developers, this text is an HTML code, and the DOM is simply called HTML DOM. Elements of HTML become nodes in the DOM.
So, while HTML is a text, the DOM is an in-memory representation of this text.
Compare it to a process being an instance of a program. You can have multiple processes of the same one program, just like you can have multiple DOMs of the same HTML (e.g. the same page loaded on many tabs).
The HTML DOM provides an interface (API) to traverse and modify the nodes. It contains methods like getElementById or removeChild
Issues
The HTML DOM is always tree-structured - which is allowed by the structure of the HTML document. This is cool because we can traverse trees fairly easily. Unfortunately, easily doesn’t mean quickly here.
The DOM trees are huge nowadays. Since we are more and more pushed towards dynamic web apps (Single Page Applications - SPAs), we need to modify the DOM tree incessantly and a lot. And this is a real performance and development pain.
BTW. I myself managed to create a web page with a source of 5GB+. It wasn’t even that hard.
Consider a DOM made of thousands of divs. Remember, we are modern web developers, our app is very SPA! We have lots of methods that handle events - clicks, submits, type-ins… A typical jQuery-like event handler looks like this:
find every node interested on an event
update it if necessary
Which has two problems:
It’s hard to manage. Imagine that you have to tweak an event handler. If you lost the context, you have to dive really deep into the code to even know what’s going on. Both time-consuming and bug-risky.
It’s inefficient. Do we really need to do all these findings manually? Maybe we can be smarter and tell in advance which nodes are to-be-updated?
Once again, React comes with a helping hand. The solution to problem 1 is declaratives. Instead of low-level techniques like traversing the DOM tree manually, you simply declare how a component should look like. React does the low-level job for you - the HTML DOM API methods are called under the hood. React doesn’t want you to worry about it - eventually, the component will look like it should.
But this doesn’t solve the performance issue. And this is exactly where the Virtual DOM comes into action.
Virtual DOM
First of all - the Virtual DOM was not invented by React, but React uses it and provides it for free.
The Virtual DOM is an abstraction of the HTML DOM. It is lightweight and detached from the browser-specific implementation details. Since the DOM itself was already an abstraction, the virtual DOM is, in fact, an abstraction of an abstraction.
Perhaps it’s better to think of the virtual DOM as React’s local and simplified copy of the HTML DOM. It allows React to do its computations within this abstract world and skip the “real” DOM operations, often slow and browser-specific.
There’s no big difference between the “regular” DOM and the virtual DOM. This is why the JSX parts of the React code can look almost like pure HTML:
#!javascript
var CommentBox = React.createClass({
render: function() {
return (
<div className="commentBox">
Hello, world! I am a CommentBox.
</div>
);
}
});
In most cases, when you have an HTML code and you want to make it a static React component, all you have to do is:
Return the HTML code in render
Replace class attribute name to className - because class is a reserved word in JavaScript.
There are more, rather minor, differences between the DOMs:
Three attributes of the virtual DOM that don’t appear in the “real” DOM - the key, ref and dangerouslySetInnerHTML.
Introducing JSX
Consider this variable declaration:
const element = <h1>Hello, world!</h1>;
This funny tag syntax is neither a string nor HTML.
It is called JSX, and it is a syntax extension to JavaScript. We recommend using it with React to describe what the UI should look like. JSX may remind you of a template language, but it comes with the full power of JavaScript.
JSX produces React “elements”. We will explore rendering them to the DOM in the next section. Below, you can find the basics of JSX necessary to get you started.
Why JSX?
React embraces the fact that rendering logic is inherently coupled with other UI logic: how events are handled, how the state changes over time, and how the data is prepared for display.
Instead of artificially separating technologies by putting markup and logic in separate files, React separates concerns with loosely coupled units called “components” that contain both. We will come back to components in a further section, but if you’re not yet comfortable putting markup in JS, this talk might convince you otherwise.
React doesn’t require using JSX, but most people find it helpful as a visual aid when working with UI inside the JavaScript code. It also allows React to show more useful error and warning messages.
With that out of the way, let’s get started!
Embedding Expressions in JSX
In the example below, we declare a variable called name and then use it inside JSX by wrapping it in curly braces:
const name = 'Josh Perez';const element = <h1>Hello, {name}</h1>;
ReactDOM.render(
element,
document.getElementById('root')
);
You can put any valid JavaScript expression inside the curly braces in JSX. For example, 2 + 2, user.firstName, or formatName(user) are all valid JavaScript expressions.
In the example below, we embed the result of calling a JavaScript function, formatName(user), into an <h1> element.
function formatName(user) {
return user.firstName + ' ' + user.lastName;
}
const user = {
firstName: 'Harper',
lastName: 'Perez'
};
const element = (
<h1>
Hello, {formatName(user)}! </h1>
);
ReactDOM.render(
element,
document.getElementById('root')
);
We split JSX over multiple lines for readability. While it isn’t required, when doing this, we also recommend wrapping it in parentheses to avoid the pitfalls of automatic semicolon insertion.
JSX is an Expression Too
After compilation, JSX expressions become regular JavaScript function calls and evaluate to JavaScript objects.
This means that you can use JSX inside of if statements and for loops, assign it to variables, accept it as arguments, and return it from functions:
function getGreeting(user) {
if (user) {
return <h1>Hello, {formatName(user)}!</h1>; }
return <h1>Hello, Stranger.</h1>;}
Specifying Attributes with JSX
You may use quotes to specify string literals as attributes:
const element = <div tabIndex="0"></div>;
You may also use curly braces to embed a JavaScript expression in an attribute:
const element = <img src={user.avatarUrl}></img>;
Don’t put quotes around curly braces when embedding a JavaScript expression in an attribute. You should either use quotes (for string values) or curly braces (for expressions), but not both in the same attribute.
Warning:
Since JSX is closer to JavaScript than to HTML, React DOM uses camelCase property naming convention instead of HTML attribute names.
For example, class becomes className in JSX, and tabindex becomes tabIndex.
Specifying Children with JSX
If a tag is empty, you may close it immediately with />, like XML:
const element = <img src={user.avatarUrl} />;
JSX tags may contain children:
const element = (
<div>
<h1>Hello!</h1>
<h2>Good to see you here.</h2>
</div>
);
JSX Prevents Injection Attacks
It is safe to embed user input in JSX:
const title = response.potentiallyMaliciousInput;
// This is safe:
const element = <h1>{title}</h1>;
By default, React DOM escapes any values embedded in JSX before rendering them. Thus it ensures that you can never inject anything that’s not explicitly written in your application. Everything is converted to a string before being rendered. This helps prevent XSS (cross-site-scripting) attacks.
JSX Represents Objects
Babel compiles JSX down to React.createElement() calls.
These two examples are identical:
const element = (
<h1 className="greeting">
Hello, world!
</h1>
);
const element = React.createElement(
'h1',
{className: 'greeting'},
'Hello, world!'
);
React.createElement() performs a few checks to help you write bug-free code but essentially it creates an object like this:
// Note: this structure is simplified
const element = {
type: 'h1',
props: {
className: 'greeting',
children: 'Hello, world!'
}
};
These objects are called “React elements”. You can think of them as descriptions of what you want to see on the screen. React reads these objects and uses them to construct the DOM and keep it up to date.
Comments
Post a Comment