Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery .on() method with multiple event handlers to one selector

People also ask

What is on () method in jQuery?

The on() method attaches one or more event handlers for the selected elements and child elements. As of jQuery version 1.7, the on() method is the new replacement for the bind(), live() and delegate() methods.

Can we have more than one event handler method for same event?

Answer. By passing an anonymous function, or a named function, with multiple event handler calls as the function body, to our event listener (like onClick , onKeyUp , onChange , etc) we can call multiple event handlers in response to a single event.

Can we use two events together in jQuery?

jQuery also allows you to bind multiple event handlers to events. For example, you could bind three different event handler functions to a page element's click event like this, where you call the bind( ) function three different times: $('#target') .


That's the other way around. You should write:

$("table.planning_grid").on({
    mouseenter: function() {
        // Handle mouseenter...
    },
    mouseleave: function() {
        // Handle mouseleave...
    },
    click: function() {
        // Handle click...
    }
}, "td");

Also, if you had multiple event handlers attached to the same selector executing the same function, you could use

$('table.planning_grid').on('mouseenter mouseleave', function() {
    //JS Code
});

If you want to use the same function on different events the following code block can be used

$('input').on('keyup blur focus', function () {
   //function block
})

I learned something really useful and fundamental from here.

chaining functions is very usefull in this case which works on most jQuery Functions including on function output too.

It works because output of most jQuery functions are the input objects sets so you can use them right away and make it shorter and smarter

function showPhotos() {
    $(this).find("span").slideToggle();
}

$(".photos")
    .on("mouseenter", "li", showPhotos)
    .on("mouseleave", "li", showPhotos);

And you can combine same events/functions in this way:

$("table.planning_grid").on({
    mouseenter: function() {
        // Handle mouseenter...
    },
    mouseleave: function() {
        // Handle mouseleave...
    },
    'click blur paste' : function() {
        // Handle click...
    }
}, "input");

Try with the following code:

$("textarea[id^='options_'],input[id^='options_']").on('keyup onmouseout keydown keypress blur change', 
  function() {

  }
);