Let’s work with JavaScript Events

As we discussed in previous blog (Basics of  Events in JavaScript) about some event names, There are some many other events are in JavaScript ,
Some Events are used with Media Elements in HTML: 
  • ·         onabort
  • ·         oncanplay
  • ·         oncalplaythrough
  • ·         ondurationchange
  • ·         onended
  • ·         onerror
  • ·         onlodeddata
  • ·         onloadedmetadata
  • ·         onloadstart
  • ·         onpause
  • ·         onplay
  • ·         onplaying
  • ·         onprogress
  • ·         onratechange
  • ·         onreadystatechange
  • ·         onseeked
  • ·         onseeking
  • ·         onstalled
  • ·         onsuspended
  • ·         ontimeupdate
  • ·         onvalumechange
  • ·         onwaiting

Some Events which are very important for our Browser:
  • ·         onafterprint
  • ·         onbeforeprint
  • ·         onbeforeload
  • ·         onblur
  • ·         onerror
  • ·         onfocus
  • ·         onhaschange
  • ·         onload
  • ·         onmessage
  • ·         onoffline
  • ·         ononline
  • ·         onpagehide
  • ·         onpageshow
  • ·         onpopstate
  • ·         onredo
  • ·         onresize
  • ·         onstorage
  • ·         onundo
  • ·         onunload

So these are some important events which are used in JavaScript for making a webpage more interactive.
Now Let’s do some live work with these events, Yet we can’t discuss all events but some important event can be discussed.

onload   Event:  The online event triggers when a Website loads in a browser. This event is defined in the BODY element. Let’s write some HTML code

Here we have defined the onload event in the BODY element, which displays an alert box showing the text, Welcome to My World!, when a web page loads. The output for the above code will be:





So this was a little bit about the onload Event, do some more Exercise from yourself and put the problems.




onsubmit  Event:  The onsubmit event is used with the FORM element and triggered  when the form is submitted. Let’s create a form and understand the onsubmit event, HTML code :


The above code is for FORM, here we added some fields like Name, Phone, Address, Email id. Next we have defined the onsubmit event in the FORM element, which displays the some message.
After filling this form when we click on submit button then alert box appears and shows the Text message:





So these are the examples of JavaScript Events.

Note : Now do exercise from yourself and put the question in Comment.
 

Basics of Events in JavaScript

Events refer to the actions that are detected by a programming language when you perform a particular task.
Example: the onclick event detected by the programming language when you click the mouse button.
Events are generally used in combination with the function, implying that when an event occurs, it calls a specified function. An event commonly occurs when a user clicks the mouse button , web page is loaded, or from field is changed. Events are handled by a special function, known as event handler, which handles a particular event when the event is triggered.
How to Create an Event handler  :
In the above code OnEvent  refers to the name of an event  followed by an equal sign and the code that executes when the event is triggered.
Let’s do some Exercise :
Working with onclick Event :
The onclick event triggers when you click a particular control, such as button control. Let’s create a webpage to understand the onclick event  :
 Here we defined the onclick event that occurs when we click on ‘Click me ‘ button.
See Output.
Here this alert box appears because of onclick  event and this event occurs when we hit on ‘Click me’ button.
So this is a basic concept of Event,. There are so many Events which are used in JavaScript with HTML. Like some JavaScript  events used in HTML forms are given below :
Some Keyboard Events which are used in HTML:
·         onkeydown
·         onkeypass
·         onkeyup
Some JavaScript mouse events used in HTML
·         onclick
·         ondblclick
·         ondrag*
·         ondragend*
·         ondragenter*
·         ondragleave*
·         ondragover*
·         ondragstart*
·         ondrop
·         onmousedown
·         onmousemove
·         onmouseout
·         onmouseover
·         onmouseup
·         onmousewheel*
·         onscroll*

      *New in HTML5

Etc there are many other Events in JavaScript Which are used in Media elements of HTML and browser. Try with these events yourself. I will discuss these and many other events with working in my Next Post.

  I

  

Calling Function with Timer in JavaScript

In JavaScript timer is the most important feature, it allows us to execute JavaScript function after a specified period; thereby, making it possible to add a new dimensions, time, to our website. With the help of timer , we can run a command at the specified intervals, run loops repeatedly at a predefined time, and synchronize multiple events in a particular time span.

There are various methods for using it:


           1.      The setTimeout() method:  Executes code at a specified interval. Syntax for this : 
                                                           setTimeout(function, delayTime)
In the above syntax the setTimeout() method contains two parameters – function and delayTime. The function parameter specifies the method that the timer calls and the delayTime parameter specifies the number of milliseconds to wait before calling the method.

Example :Let’s try with an example, this method is useful when we want to delay the execution of a particular code.  Let’s write a code :

The setTimeout(“alert(‘Hi, Welcome! Ankur Here.’)”, 5000) method is used to create a timed alert box. The first parameter of the setTimeout() method is a string that contains a JavaScript statement, alert(‘Hi, Welcome! Ankur Here.’), and 2ndparameter , 5000 , specifies the time in milliseconds after which the first parameter will esecute.
So output of this code will be:



      2.      The clearTimeout() method:  Deactivates or cancels the timer that is set using the setTime() method.    Syntax for this :
clearTimeout(timer)

in the above syntax , timer is a variable that is created using the setTimeout() method.
      3.      The setInterval() method : Executes a function after specified time interval. The syntax for this :
setInterval(function, intervalTime)

In above syntax the setInterval() is the method contains two parameters- function and intervalTime. The function parameters specifies the method to be called; whereas, the intervalTime parameter specifies the time interval between the function calls.
Example :Let’s try with an example, this method is used to execute the code after every specified time intervals.  Let’s write a code:




In given code the setInterval() method is used to create a timer that calls the alert() method repeatedly. In the setInterval() method, the first parameter is a string that contains a JavScript statement, alert(‘Sorry ! 1 seconds.’). The second parameter specifies the time in milliseconds, 1000, after which the first parameter is displayed.

So the Output of this code will be :

      4.      The clearInterval() method: Deactivates or cancels the timer that is set using the setInterval() method.     The syntax for this :
clearInterval(timer)
The preceding syntax deactivates the inner timer variable that is created using the setInterval() method.

So Enjoy and work with Timer in JavaScript.

Function in JavaScript

All of us know function is a collection of statements that is executed when it is called at some point in a program. A function performs a specific task within a program independent of the rest code in the program. We can call the function from anywhere within a program. We can also define the parameters to be passed with function while calling the function. The parameters in a function are used to exchange information between a calling statement and function. We can define a function by using the function keyword.
Syntax for a function :

Above syntax has name of function, and parameters of a function.

JavaScript functions are divided into two categories:



Function without Parameters: Does not contain parameters. This code written in these function is static, implying that the values of members of these function cannot be changed at runtime.
Function with parameters:  Contains parameter in its parenthesis, such as integer and string. Unlike function without parameters, the values of members of these function can be changed at run time by passing different values of their parameters.

Now let’s understand the JavaScript function using a simple example:



We have created a function named simple under the head section.

The simple() function an alert message with Thank you.

The onload event handler under the BODY element calls simple() function when the document is loaded in the browser.
Output :

Selection Statements in JavaScript

Suppose there is  a web page in our shopping website, which accepts a price range from the users. When the users provide a price range, the items or products that lie within the specified price range displayed. Such functionality and logic can be incorporated by using selection statement in the script.
Selection statement use a condition to selector determine the statement that are to be executed. These statements help us to make decisions and change the flow of execution of the statements. In the JavaScript, there are three selection statements :
  1.         If
  2.       .  If….else
  3.      .   Switch

Let’s know more about these statements:


The if Statement : The if statement is one of the most basic and simplest control flow statement. We can use the if statement when we want to execute a group of one or more script statements only when a particular condition is met.
Syntax :
            If(condition)
            {
              Statement 1
            }
In the preceding syntax, if JavaScript keyword that signifies an if statement and contain a condition, which need to be evaluated to true, then the script statement, represented by statement 1, enclosed within the curly braces is executed. If the condition evaluates to false, then the statement enclosed within the curly braces skipped and the statement immediately after closing curly brace(}) is executed.

Let’s Understand :  A simple example for If Statement is given below:

<!DOCTYPE HTML>
<HTML>
                <HEAD>
                                <TITLE>Using if Statement</TITLE>
                </HEAD>
                <BODY>
                                <H1>Using the if Statement in the script </H1>
                                <SCRIPT type=”text/javascript”>
                                                var Number=45;
                                                if((Number%2) != 0)
                                                {
                                                                document.write(Number + ” is an odd number”);
                                                }
                                                document.write(“<BR/>Thank you!”);
                                </SCRIPT>
                </BODY>
</HTML>
Output:
 

The if…..else statement:As we know the if statement allows us to execute a set of statements only when a particular condition is true. However, if we want to execute another set of statements when the condition is false, then we can use the if….else statement.
Syntax:
            If(condition)
            {
            Statement 1
            }
            Else
            {
Statement  2
}
In the given syntax, if and else keywords that signify the if…else statement. The condition of the if….else statement if enclosed within parentheses. If the condition is true, then the group of statements represented by statement 1 enclosed within the first curly braces is executed. If the condition is false, then the statement 1 is skipped and the group of statements, represented by statement 2 of the else block is executed.

Let’s Try: A simple if else Statement is given below :

<!DOCTYPE HTML>
<HTML>
                <HEAD>
                                <TITLE>if…else Statement</TITLE>
                </HEAD>
                <BODY>
                                <H1>Using the if…else Statement in the Script</H1>
                                <SCRIPT type=”text/javascript”>
                                                var Number=44;
                                                if((Number%2) != 0)
                                                {
                                                                document.write(Number + ” is an odd number”);
                                                }
                                                else
                                                {
                                                                document.write(Number + ” is an even  number”);
                                                }
                                                document.write(“<BR/>Thank you!”);
                                </SCRIPT>
                </BODY>
</HTML>
Out Put :

The switch statement:A switch statement is used to select a particular group of statements to be executed among several other groups of statements. The group of statements that is to be executed is selected on the basis of a numeric or string expression.
Syntax:
            switch(expression)
            {
case value1:statement 1
            break;
case value2:statement 2
            break;
case value3: statement 3
            break;
default:statement_default
            break;
}
In given syntax, switch case, and break are JavaScript keywords. The switch keyword indicates the switch statement. In a switch statement the expression that is to be evaluated is specified within parentheses. This expression is checked against each of the case values specified in the case statements. If any of the case values match the value of the expression, the group of statement (statement 1, statement 2 or statement 3) specified in the respective case statement is executed. If none of the case values matches the value of the expression, then the default statement, specified by the default keyword, is executed. The default statement is generally placed at the end of the switch statement; however, we can place it anywhere within the switch statement.


   Let’s Try: A simple example for Switch statement is given below :


<!DOCTYPE HTML>
<HTML>
                <HEAD>
                                <TITLE>Using switch Statement</TITLE>
                </HEAD>
                <BODY>
                                <H1>Using switch Statement in the script</H1>
                                <SCRIPT type=”text/javascript”>
                                                var letter=”I”;
                                                switch(letter)
                                                {
                                                                default:document.write(“consonant”);
                                                                                break;
                                                                case “A”:document.write(“A is a vowel”);
                                                                                break;
                                                                case “E”:document.write(“E is a vowel”);
                                                                                break;
                                                                case “I”:document.write(“I is a vowel”);
                                                                                break;
                                                                case “O”:document.write(“O is a vowel”);
                                                                                break;
                                                                case “U”:document.write(“U is a vowel”);
                                                                                break;
                                                }
                                                document.write(“<BR/>Thank You!”);
                                </SCRIPT>
                </BODY>
</HTML>
Output:

JavaScript in HTML Document

For this we can follow three ways, which are given below:
1.      JavaScript in HEAD Element
2.      JavaScript in BODY Element
3.      As an External Script File
    
JavaScript in HEAD Element:  We can use JavaScript in HEAD section by given Method. The script placed inside the HEAD element runs when you perform some action, such as click a link or the submit button.
Code Syntax:
<HEAD>
<SCRIPT type=”text/javascript”>
Script code here
</SCRIPT>
</HEAD>
Example:
<!DOCTYPE HTML>
<HTML>
                <HEAD>
                                <TITLE>JavaScript in HEAD Element</TITLE>
                                <H1>Adding script in the HEAD Element</H1>
                                <SCRIPT type=”text/javascript”>
                                                document.write(“Welcome to the World of JavaScript
<BR/>”);
                                                document.write(“In this example we have used the
JavaScript in the HEAD element.”);
                                </SCRIPT>
                </HEAD>
</HTML>
Output:
JavaScript in BODY Element:  We can use JavaScript in BODY section by given Method. The script placed inside the BODY element runs when a web page start loading ia a web browser.
Code Syntax:
<BODY>
<SCRIPT type=”text/javascript”>
Script code here
</SCRIPT>
</BODY>
Example:
<!DOCTYPE HTML>
<HTML>
                <HEAD>
                                <TITLE>JavaScript in BODY Elementt</TITLE>
                </HEAD>
                <BODY>
                                <H1>Adding JavaScript in Body Element</H1>
                                <SCRIPT type=”text/javascript”>
                                                document.write(“Welcome to the World of JavaScript
<BR/>”);
                                                document.write(“In this example we have used the
JavaScript in the BODY element.”);
                                </SCRIPT>
                </BODY>
</HTML>
Output:

JavaScript as an EXTERNAL Script File:  When JavaScript code created in an HTML file is very lengthy; It affects the readability of the HTML file. In addition, at times we may need to use the same JavaScript code in several Web pages. In such cases, we can store the JavaScript code in an External file and save that file using the ‘.js’ extension. Next we need to link the external file with the HTML document by using ‘src’ attribute of the SCRIPT element to access the script file.
Code Syntax:
<HEAD>
<SCRIPT src=URL of the External .js file>
Script code here
</SCRIPT>
</HEAD>
Example:
<!DOCTYPE HTML>
<HTML>
                <HEAD>
                                <TITLE>JavaScript as an EXTERNAL Script File</TITLE>
                </HEAD>
                <BODY>                              
                                <H2>The sum of First Four Number is:</H2>
                                <H2><script src=”MyScript.js”></H2>
                                </SCRIPT>
                </BODY>
</HTML>
External JavaScript :
var i, count=0;
for(i=0;i<5;i++)
{
                count=count+i;
}
document.write(count);

Output:

Now Let’s Start with JavaScript

We all know About JavaScript:
     ·   Object Based Scripted Language
     ·   Light Weight programming Language with less Complexity
     ·   Most commonly used Language to add Dynamism and interactivity
     ·   Client and Server Side object based Scripted Language
And many more things.

Formally JavaScript was known as LiveScript, and developed by NetScape and Sun Microsystem. It is also known as ECMAScript as it was standardized by  “European Computer Manufacture’s Association” .
Now Let’s talk about the Key Features of JavaScript :

1.     Dynamic Text:  This means that the type of variable is defined according to the value stored in it.  For Example: After declaring a variable x, we can assign it a number or string value. This is known as dynamic typing. JavaScript is an object based Scripting language, which provides some built-in objects, such an String, Math and Data objects.

2.     Functional:  It implies that JavaScript does not support ‘classes’. Instead of using classes , objects are created from the constructor  function. Each constructor function represents a unique object type.

3.     Prototype-based:  Implies that JavaScript is a prototype-based language. This means that JavaScript uses prototype instead of classes for inheritance. In JavaScript, each constructor function is associated with a prototype object. There are several built-in objects that represents constructor functions such as
·        Array()
·        Boolean()
·        Data()
·        Error()
·        Math()
·        Number()
·        Number()
·        Object()
·        RegExp()
·        String()
4.      Imperative and structured:  Implies that JavaScript supports all the Syntaxes of the structured programming language ‘C’, such as ‘If’ statement, ‘Loop’ and ‘Switch’ statements. The Only difference between C and JavaScript is that in JavaScript semicolon is not necessary to terminate the statement whereas in C semicolon is necessary to terminate the statement.

5.      Platform Independent:  Implies that JavaScript supports platform-independency or we can Say Portability. We can write our JavaScript application and run it on any platform or any browser without affecting the Output of the script.

JavaScript in HTML Document, Using <SCRIPT> Element:

For this we can follow three ways, which are given below:

1.      JavaScript in HEAD Element
2.      JavaScript in BODY Element
3.      As an External Script File
     
JavaScript in HEAD Element:  We can use JavaScript in HEAD section by given Method. The script placed inside the HEAD element runs when you perform some action, such as click a link or the submit button.
Code Syntax:
<HEAD>
<SCRIPT type=”text/javascript”>
Script code here
</SCRIPT>
</HEAD>
JavaScript in BODY Element:  We can use JavaScript in BODY section by given Method. The script placed inside the BODY element runs when a web page start loading ia a web browser.
Code Syntax:
<BODY>
<SCRIPT type=”text/javascript”>
Script code here
</SCRIPT>
</BODY>
JavaScript as an EXTERNAL Script File:  When JavaScript code created in an HTML file is very lengthy; It affects the readability of the HTML file. In addition, at times we may need to use the same JavaScript code in several Web pages. In such cases, we can store the JavaScript code in an External file and save that file using the ‘.js’ extension. Next we need to link the external file with the HTML document by using ‘src’ attribute of the SCRIPT element to access the script file.
Code Syntax:
<HEAD>
<SCRIPT src=URL of the External .js file>
Script code here
</SCRIPT>
</HEAD>