jQuery multiple events to trigger same function

By Faruque Ahamed Mollick

I hope this post is going to be interesting to you. Here in this post, I am going to tell you how to trigger a function with multiple JavaScript events.

Triggering the same function with multiple events is often required. Well, this task is very easy using jQuery. Using jQuery on() method this task can be done. We can easily pass multiple events with jQuery on() method. this is an easy, simple and nice way.

Disable right click, copy, cut on web page using jQuery



Live word counter from HTML textarea in JavaScript

Below is the jQuery code structure which shows you how to trigger or call just one function with multiple events:

$('#my_element').on('keyup keypress change', function(e) {
    // Your code goes here
});

On the above code, you can see how we have trigger one function with three events that are keyup, keypress and change event. Inside the on() method, in the first parameter, we put multiple event names separated by space. The same function will be called every time one of these three events will occur.

Now we are going to give an example. In this example, we have a text type input field. Now we are going to show the text that we will type inside the text input box will be displayed in live. Here we are going to use three events that will call just one function.

Immediately submit upload form after selecting file

Now below is our HTML code for text input field and another element that will display the text we are going to type in the input box live:

<input type="text" id="myInput">
<br/>
<span id="showtext"></span>

And below is our jQuery code:

$('#myInput').on('keyup keypress change', function(e) {
     var input_value = $('#myInput').val();
     $('#showtext').text(input_value);
});

We want to display our typed text when we press the key, when we leave key after pressing and when we change the value inside the text box. So, for this reason, we have used three events that can be used for our specific task.

Leave a Reply

Your email address will not be published. Required fields are marked *