jQuery Event Handling

Rumman Ansari   Software Engineer   2023-03-23   188 Share
☰ Table of Contents

Table of Content:


Event Handling in jQuery
  • Events are actions that are performed by the user or the browser in a web page.

  • For example a mouse click, keypress are the events performed by a user and page load is an event that is performed by the browser.

  • Events do the real magic in making the web page dynamic.

  • Event handlers are the functions that are executed when an event occurs.

Are you excited to know how does jQuery handles events? Keep going.

Using Events in jQuery
  • You can associate any element in a HTML document with an event.

  • Just choose the target element with the help of selector and then use the required event using dot operator

  • Some frequently used events are: click(), focus(), blur(), hover(), etc.

jQuery Events - Usage

To add a click event to an element with id "fresco":


$("#atnyla").click()

Now you should specify what should happen when the event occurs. This should be done by passing a function to the event


$("#atnyla").click(
function(){
console.log("This is an event");
});

Let us explore some important methods related to events in upcoming cards.

on() Method

Consider a scenario where you want to perform multiple actions on single element. This is where on() method comes into play. It helps in adding one or more event handlers to an element.

Syntax :


$(anyElement).on( events [, selector ] [, dataForHandler ], handlerFunction )

Here the parameters are not mandatory. This will attach the on() method to the corresponding parent element and the selector parameter will be a child element.


on() Method - Examples

Single event handler


$("div").on("click", function(){
  console.log("using on() with single event handler");
});

Multiple event handler


$("p").on({
    click: function(){
       console.log("This is click event");
    }, 
    mouseover: function(){
       console.log("This is hover event");
    }
});

Event Delegation
  • In on() method, if the selector is not passed then it is called Direct event else it is called Delegate event.

  • Event Delegation is the process of adding an event to a parent element which will be fired only when the selector parameter in on() function matches with the child elements(decendence).

  • Advantage of using this is that the event handler will not only be appended to the existing decendence but also to all the decendence that will be added in future.

Event Delegation - Example
  • This example will demonstrate how event delegation in resourceful.

Codepen- Event Delegation



<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script> 
	$(document).ready(function () { 
    $('ul').on('click', 'li', function () {
      $(this).fadeOut(600); 
    });
    
    $('#btn').click( function () { 
      $('ul').append('<li>New Item</li>');
    });
   
  }); 
  </script>
</head>
<body>
  <input id="btn" type="button" value="Add" /> 
  <ul>
      <li>atnyla item 1</li> 
      <li>atnyla item 2</li> 
  </ul>
</body>

  • Here there are only two elements in the list initially and the on method will add event handlers to them.

  • A new item is added only after the on() method executes but still the jQuery appends the event handler to the newly added elements.

This explains the advantage of using the event delegation in webpages.


off() Method

Now you know how to add a event handler to an element, what if you want to remove a event handler from an element?

Here comes off() method which will do that job.

Usage

This method accepts three parameters, the event name, selector and the event handler. These parameters are not mandatory.


$("body").off( "click", "#fresco", myfunction );

You can also use $("body").off() to remove all the event handlers associated with the selector.

Similarly $("body").off("click"); will remove all the click events.


preventDefault()
  • Some elements in HTML have default behavior attached to them, such as a anchor tag opening an url in the browser.

  • In case you want to override that behavior in your page then jQuery helps you with preventDefault() method.

  • This method has no parameters.

  • Just call the method wherever required and the default action of that element will be terminated.

For the complete set of events and methods available in jQuery refer

jQuery-Events