Javascript Events

A change in state of an object is known as an Event. In html, there are multiple events which defines that some activity is done or performed by the user or by the browser like chrome, firefox. When javascript code is included in HTML, js react over to these events and allow the execution. This phenomena  of reacting over the events is called Event Handling. Thus, js handles the HTML events via Event Handlers.

For example, when a user clicks over the browser, add js code, which will execute the task to be performed on the event.

Here are some examples of HTML events:

•           An HTML web page has finished loading(images, videos, libraries)

•           An HTML input field was changed

•           An HTML button was clicked

Some of the HTML events and their event handlers are given below:


Mouse Event

Event PerformedEvent HandlerDescription
clickonclickWhen mouse click on an dom element
mouseoveronmouseoverWhen the cursor of the mouse comes over the dom element
mouseoutonmouseoutWhen the cursor of the mouse leaves an dom element
mousedownonmousedownWhen the mouse button is pressed over the dom element
mouseuponmouseupWhen the mouse button is released over the dom element
mousemoveonmousemoveWhen the mouse movement takes place.
Keydown & Keyuponkeydown & onkeyupWhen the user press and then release the key

Form events

Event PerformedEvent HandlerDescription
focusonfocusWhen a user focuses on an element
submitonsubmitWhen a user submits the form
bluronblurWhen the focus goes away from a form element
changeonchangeWhen a user modifies or changes the value of a form element

Window/Document events

Event PerformedEvent HandlerDescription
loadonloadWhen the browser finishes the loading of the page(images, videos, libraries)
unloadonunloadWhen a visitor leaves the current webpage, the browser unloads it
resizeonresizeWhen a visitor resizes the window of the browser

Let’s discuss some examples for the above discussed events and their handlers.



Click Event

Input:-

<!DOCTYPE html>
<html>
   <head>
      <title>This page title</title>
   </head>
   <body>  
      <form>  
         <input type= "button" onclick= "clickevent()" value= "Click Here!"/>  
      </form>            
      <script>
         function clickevent(){  
            alert("user clicked!")
         }  
      </script>
   </body>
</html>

Output:-


Keydown Event

Input:-

<!DOCTYPE html>
<html>
   <head>
      <title>This page title</title>
   </head>
   <body>  
      <h2> Enter something here</h2>  
      <input type= "text" id= "name" onkeydown= "keydownAction()"/>          
      <script>
         function keydownAction(){  
            document.getElementById("name");  
            alert("Pressed a key");  
         }  
      </script>
   </body>
</html> 

Output:-



Load Event

Input:-

<!DOCTYPE html>
<html>
   <head>
      <title>This page title</title>
   </head>
   <body onload="window.alert('Page loaded successfully');">  
      <script>  
      document.write("Page is loaded successfully");       
      </script>
   </body>
</html>

Output:-



JavaScript addEventListener()

The addEventListener() method is used to bind an event handler to a specific element. It does not override the existing event handlers. Events are said to be an essential or important part of the JavaScript.

This method is an inbuilt or predefined function of JavaScript. We can add various event handlers to a particular element without overwriting the existing event handlers.

Syntax:-
   
element.addEventListener(event, function, useCapture);

    Parameter Values

event: It is a mandatory parameter. It can be defined as a string that tells the event’s name.

     Note:- Do not use any prefix such as “on” with the parameter value. For example, Use “click” instead of using “onclick”.

function: It is also a mandatory parameter. It is a JavaScript function which responds over the event occur.

useCapture: It is an optional parameter. It is a Boolean type value that specifies whether the event is executed in the bubbling or capturing phase. Its possible values are true and false. When it is set to true, the event handler executes in the capturing phase. When it is set to false, the handler executes in the bubbling phase. Its default value is false.

Let’s discuss some of the examples of using the addEventListener() method.

Input:-
   
<!DOCTYPE html>  
<html>
   <body>
      <p> addEventListener() Example </p>
      <p> Click button </p>
      <button id = "btn"> Click here </button>  
      <p id = "pgraph"></p>
      <script>  
         document.getElementById("btn").addEventListener("click", test);  
         function test() {  
         document.getElementById("pgraph").innerHTML = "Hello World" + "<br>" + "Welcome to my world";  
         }  
      </script>  
   </body>
</html>

Output(Before Click):-

Output(After Click):-


Event Bubbling or Event Capturing

Syntax:-
   
addEventListener(event, function, useCapture);

Now, we will understand the benefit of the third optional parameter of JavaScript’s addEventListener(), i.e., useCapture.

In HTML DOM, Bubbling and Capturing are the two different ways of event propagation. We will understand these ways by taking an example.

Suppose we have a div element and a paragraph element inside it, and we are applying the “click” event to both of them using the addEventListener() method. Now the question is on clicking the paragraph element, which element’s click event is handled first.

So, in Bubbling, the event for paragraph element will be handled first, and then the div element’s event will be handled. It means that in bubbling, the inner element’s event is handled first, and then the outermost element’s event will be handled.

In Capturing the event for div element will be handled first, and then the paragraph element’s event will be handled. It means that in capturing the outer element’s event is handled first, and then the innermost element’s event will be handled.

Input:-
   
<!DOCTYPE html>  
<html>
   <head>
      <style>  
         div{  
         background-color: yellow;  
         border: 3px solid green;  
         font-size: 23px;  
         text-align: center;  
         }  
         p{  
         border: 2px solid red;  
         }  
      </style>
   </head>
   <body>
      <h1> Bubbling </h1>
      <div id = "div1">
         This is a div element.  
         <br><br>  
         <p id = "p1"> This is a p element. </p>
      </div>
      <h1> Capturing </h1>
      <div id = "div2">
         This is a div element.  
         <br><br>  
         <p id = "p2"> This is a p element. </p>
      </div>
      <script>  
         document.getElementById("div1").addEventListener("dblclick", function() {alert('You have double clicked on div element')}, false);  
         document.getElementById("p1").addEventListener("dblclick", function() {alert('You have double clicked on p element')}, false);  
         document.getElementById("div2").addEventListener("dblclick", function() {alert('You have double clicked on div element')}, true);  
         document.getElementById("p2").addEventListener("dblclick", function() {alert('You have double clicked on p element')}, true);  
      </script>  
   </body>
</html>

Output(Before Click):-

Output(Event Bubbling – After Click):-

Output(Event Capturing – After Click):-


JavaScript onclick event

The onclick event often occurs when a user clicks on an element. It allows the programmer to execute a JavaScript’s function when a dom element gets clicked. This event can be used in many aspects like validating a form, warning messages and many more.

Using JavaScript, this event can be dynamically or runtime added to any element. It supports all HTML elements except <html>, <head>, <title>, <style>, <script>, <base>, <iframe>, <bdo>, <br>, <meta>, and <param>. It means we cannot apply the onclick event on the above tags.

Now, we will see the syntax of using the onclick event in HTML and in javascript (without addEventListener() method).

In HTML

<element onclick = “myFunc()”> 

In the below example, we are using the HTML onclick attribute and assigning a JavaScript’s function on it. When the user clicks the button, the defined function will get executed, and an alert box will be displayed.

Input:-
   
<!DOCTYPE html>  
<html>
   <head>
      <script>  
         function myFunc() {  
         alert("Welcome to my world");  
         }  
      </script>  
   </head>
   <body>
      <h3> Example of using onclick attribute in HTML. </h3>
      <p> Click button </p>
      <button onclick = "myFunc()">Click here</button>  
   </body>
</html>

Output(Before Click):-

Output(After Click):-

In Javascript

object.onclick = function() { myJavaScript }; 

In the below example, we are using JavaScript’s onclick event. Here we will be using the onclick event with the paragraph element.

When a user clicks on the paragraph element, the defined function will get executed, and the text of the paragraph and background color of the text gets changed.

Input:-
   
<!DOCTYPE html>  
<html>
   <head>
      <title> onclick event </title>
   </head>
   <body>
      <h3> Example of using onclick event. </h3>
      <p id = "pgraph">Click me</p>
      <script>  
         document.getElementById("pgraph").onclick = function() {  
         myfunc()  
         };  
         function myfunc() {  
         document.getElementById("pgraph").innerHTML = "Welcome to my world";  
         document.getElementById("pgraph").style.backgroundColor = "lightgreen";  
         }  
      </script>  
   </body>
</html>

Output(Before Click):-

Output(After Click):-

In JavaScript by using the addEventListener() method

object.addEventListener(“click”, myJavaScript );

In the below example, we will be using JavaScript’s addEventListener() method to bind a click event to the paragraph element. When the user clicks the paragraph element, the text of the paragraph and font-size of elements gets changed.

Input:-
   
<html>
   <head>  </head>
   <body>
      <h3> Example of using click event. </h3>
      <p id = "pgraph">Click here</p>
      <script>  
         document.getElementById("pgraph").onclick = function() {  
         fun()  
         };  
         function fun() {  
         document.getElementById("pgraph").innerHTML = "Welcome to myworld";    
         document.getElementsByTagName("p")[0].style.fontSize = "25px";  
         }  
      </script>  
   </body>
</html>

Output(Before Click):-

Output(After Click):-


JavaScript dblclick event

         The dblclick event fires an event on double click of  an element. The event fires      when an element is clicked two times in a very short duration of time.

Now, we will see the syntax of creating double click event in HTML and in javascript (without using addEventListener() method or by using the addEventListener() method).

In HTML

<element ondblclick = “myFunc()”> 

Input:-
   
<!DOCTYPE html>  
<html>
   <head>  </head>
   <body>
      <p> Example of using the <b> ondblclick </b> attribute. </p>
      <h1 id = "h1" ondblclick = "myFunc()"> Double click here </h1>
      <script>  
         function myFunc() {  
         document.getElementById("h1").innerHTML = " Welcome to my world! ";  
         }  
      </script>  
   </body>
</html>

Output(Before Click):-

Output(After Click):-

In Javascript

object.ondblclick = function() { myJavaScript }; 

Input:-
   
<!DOCTYPE html>  
<html>
   <head>  </head>
   <body>
      <p> Example of using the <b> ondblclick </b> JavaScript. </p>
      <h1 id = "h1"> Double click here </h1>
      <script>  
         document.getElementById("h1").ondblclick = function() { myFunc() };  
         function myFunc() {  
         document.getElementById("h1").innerHTML = " Welcome to my world! ";  
         }  
      </script>  
   </body>
</html>

Output(Before Click):-

Output(After Click):-

In JavaScript by using the addEventListener() method

object.addEventListener(“dblclick “, myJavaScript );

Input:-
   
<!DOCTYPE html>  
<html>
   <head>  </head>
   <body>
      <p> Example of using the <b> ondblclick using the <b> addEventListener() method. </p>
      <h1 id = "h1"> Double click here </h1>
      <script>  
         document.getElementById("h1").addEventListener("dblclick", myFunc);   
         function myFunc() {  
         document.getElementById("h1").innerHTML = " Welcome to my world! ";  
         }  
      </script>  
   </body>
</html>

Output(Before Click):-

Output(After Click):-


JavaScript onload Event

In JavaScript, the event can apply to fire a particular function when the page is fully loaded. It can also be used to detect the type and version of the client’s browser.

In HTML, the onload attribute fires when an dom object has been fully loaded with images, video, libraries etc. The purpose of this attribute is to execute a javascript code when the relative element loaded.

In HTML, the onload attribute is generally used with the <body> tag to execute a script once the content (including CSS files, images, scripts, etc.) of the webpage is fully loaded.

     Note:- It is not necessary to use it only with <body> tag, as it can be used with other HTML elements.

The main difference between the document.onload and window.onload is: document.onload triggers before the loading of images and other external content or libraries. It is fired before the window.onload. other hand the window.onload triggers when the full page loads, including CSS files, script files, images, external libraries etc.

Syntax:-
   
window.onload = myFunc()  

Example 1-

In the below example, there is a div element with a height of 100px and a width of 100px. Here, we are using the window.onload() to change the background color, width, and height of the div element after loading the full web page.

The background color is set to ‘yellow’, and width and height are set to 150px each.

Input:-
   
<!DOCTYPE html>  
<html>
   <head>
      <meta charset = " utf-8">
      <title> window.onload() </title>
      <style type = "text/css">  
         #d1{  
         width: 100px;  
         height: 100px;  
         border: 4px solid green;  
         }  
      </style>
      <script type = "text/javascript">  
         window.onload = function(){  
         document.getElementById("d1").style.backgroundColor = "yellow";  
         document.getElementById("d1").style.width = "150px";  
         document.getElementById("d1").style.height = "150px";  
         }  
      </script>  
   </head>
   <body>
      <h2> Example of window.onload() </h2>
      <div id = "d1"></div>
   </body>
</html>

Output:-

Example 2-

Below is a small and simple example of using the HTML onload attribute with the defined function in JavaScript. In this example, the alert() function gets called whenever the document refresh.

Input:-
   
<!DOCTYPE html>  
<html>
   <head>
      <style>  </style>
      <script>  
         function myFunc() {  
            alert("Hello World!!, Welcome to my world!");  
         }  
      </script>  
   </head>
   <body onload = "myFunc()">
      <h1> HTML onload attribute </h1>
      <p> After page onload function will be called. </p>
   </body>
</html>

Output:-


JavaScript onresize event

         The onresize event in JavaScript generally fires when the window gets resized. To achieve this we can use JavaScript’s window.outerWidth and window.outerHeight events.

We can also use the JavaScript’s properties such as innerWidth, innerHeight, clientWidth, ClientHeight, offsetWidth, offsetHeight to get the size of an element.

Now, we see the syntax of using the onresize event in HTML and in javascript (without addEventListener() method or by using the addEventListener() method).

In HTML

<element onresize = “myFunc()”> 

In the below example, we will be using the HTML onresize attribute. Here, we are using the window.outerWidth and window.outerHeight events of JavaScript to get the height and width of the window.

 

Input:-
   
<!DOCTYPE html>  
<html>
   <head>
      <script>  
         var i = 0;  
           
         function myFunc() {  
         var res = "Width = " + window.outerWidth + "<br>" + "Height = " + window.outerHeight;  
         document.getElementById("pgraph").innerHTML = res;  
           
         var res1 = i += 1;  
         document.getElementById("span1").innerHTML = res1;  
         }  
      </script>  
   </head>
   <body onresize = "myFunc()">
      <h3> Example of using onresize attribute. </h3>
      <p> Try to resize the browser's window to see the change </p>
      <p id = "pgraph"> </p>
      <p> Window has resized by<span id = "span1"> 0 </span> times.</p>
   </body>
</html>

Output(Before resize):-

Output(After resize):-

In Javascript

  object.onresize = function() { myJavaScript  };    

Input:-
   
<!DOCTYPE html>  
<html>
   <head>  </head>
   <body>
      <h3> Example of using onresize attribute. </h3>
      <p> Try to resize the browser's window to see the change </p>
      <p id = "pgraph"> </p>
      <p> Window has resized by<span id = "span1"> 0 </span> times.</p>
      <script>  
         document.getElementsByTagName("BODY")[0].onresize = function() {myFunc()};
         var i = 0; 
           
         function myFunc() {  
         var res = "Width = " + window.outerWidth + "<br>" + "Height = " + window.outerHeight;  
         document.getElementById("pgraph").innerHTML = res;  
           
         var res1 = i += 1;  
         document.getElementById("span1").innerHTML = res1;  
         }  
      </script>   
   </body>
</html>

Output(Before resize):-

Output(After resize):-

In JavaScript by using the addEventListener() method

                        object.addEventListener(“resize”, myJavaScript ); 

Input:-
   
<!DOCTYPE html>  
<html>
   <head>  </head>
   <body>
      <h3> Example of using addEvent listener. </h3>
      <p> Try to resize the browser's window to see the change </p>
      <p id = "pgraph"> </p>
      <p> Window has resized by<span id = "span1"> 0 </span> times.</p>
      <script>  
         window.addEventListener("resize", myFunc);  
         var i = 0; 
           
         function myFunc() {  
         var res = "Width = " + window.outerWidth + "<br>" + "Height = " + window.outerHeight;  
         document.getElementById("pgraph").innerHTML = res;  
           
         var res1 = i += 1;  
         document.getElementById("span1").innerHTML = res1;  
         }  
      </script>   
   </body>
</html>

Output(Before Resize):-

Output(After Resize):-