jQuery multiple events to trigger same function

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. The jQuery on multiple events is an easy task.

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">
<span id="showtext"></span>

And below is our jQuery code:

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

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.

So I hope you have understood how jQuery works on multiple events. Please let me know if you have anything to tell related to this task.

Leave a Reply

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