jquery on multiple events

JQuery on multiple events

Implementing JQuery on multiple events is a common requirement in web development. It enables us to perform multiple actions when different kinds of events occur in the web application. For instance, we might want to display a pop-up when a user clicks a button, but also want to hide the pop-up when the user clicks outside the pop-up or hits the escape key.

Using .on() method

The .on() method is an effective way to bind multiple events to an element. We can attach multiple events using .on() method separated by a space.


<div id="myDiv">
  <p>Click on this div.</p>
</div>

<script>
  $(document).ready(function(){
    $('#myDiv').on('click mouseover', function() {
        alert('You clicked or hovered over myDiv!');
    });
  });
</script>

In the above example, we have attached two events, click and mouseover, to the div element with id “myDiv”. Whenever a user clicks or hovers over the div element, the alert message will be displayed.

Using .bind() method

The .bind() method is another way to attach multiple events to an element. It works like .on() method, but it is not recommended to use because it has been deprecated since JQuery version 3.0.


<div id="myDiv">
  <p>Click on this div.</p>
</div>

<script>
  $(document).ready(function(){
    $('#myDiv').bind('click mouseover', function() {
        alert('You clicked or hovered over myDiv!');
    });
  });
</script>

Using a named function

We can also attach multiple events to an element using a named function. This makes the code more reusable and easier to maintain.


<div id="myDiv">
  <p>Click on this div.</p>
</div>

<script>
  $(document).ready(function(){
    $('#myDiv').on('click mouseover', myFunction);
  });

  function myFunction() {
    alert('You clicked or hovered over myDiv!');
  }
</script>

In the above example, we have attached two events, click and mouseover, to the div element with id “myDiv” using a named function “myFunction”. Whenever a user clicks or hovers over the div element, the alert message will be displayed.

  • Using .on() method
  • Using .bind() method (deprecated)
  • Using a named function

All of the above methods are valid for attaching multiple events to an element. However, it is recommended to use the .on() method because it is more efficient and flexible than the .bind() method. Also, using a named function makes the code more organized and maintainable.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe