How can I trigger the same function from multiple events with jQuery?

Learn, how to trigger the same function from multiple events using jQuery?
Submitted by Pratishtha Saxena, on August 23, 2022

Events are some set of commands that are implemented when the function attached to it gets triggered. The most used events in jQuery are: click(), keypress(), hover(), mouseenter() and many more. These just make the user interaction more attractive and dynamic. But these when used are generally used only one at a time, which means that normally only one event is attached to the function at a time.

But it doesn't mean that more than one event cannot be attached to the function at once. Yes, many events can be linked to the same function. This is achieved by using the basic on() method of jQuery.

The on() method is used for various purposes. It is mostly used for buttons that on click trigger a function or an event attached to it. Therefore, as it works for a single event, many events can be listed together for using them simultaneously.

Syntax:

$('selector').on('event1 event2 event3 event4', function(){});

Previously you would have seen or used on() method with a single event, now above given syntax shows how can one use multiple events together attached to the same function. This means that when any of the listed events is performed, the function gets triggered.

If event2 is say hover (mouse), hence, performing it will trigger the function to run. For this, let's see an example below.

Example to trigger the same function from multiple events with jQuery

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2>Trigger Same Functions From Multiple Events Using jQuery</h2>
    <p id="myPara">Welcome To Include Help !!</p>
    <button type="button" id="button1">Click Here</button>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('#button1').on('click dblclick keypress hover mouseenter', function(){
            $('#myPara').css('background','yellow');
        })
    });    
  </script>
</html>

Output:

Example 1: Trigger the same function from multiple events with jQuery

On putting the mouse over the button or clicking it will highlight the text.

Example 2: Trigger the same function from multiple events with jQuery






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.