Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use $(document).on to bind multiple events to the same element

I'm trying to get used to the new proper way of doing things in jQuery but I can't figure out how to do a "live" binding that's as elegant/DRY as the original. Previously, with "live" I believe you could do this, only mentioning the element once:

$("#element_id").live("click",function(){
  //stuff
}).live("mouseover", function(){
  //stuff
}).live("mouseout", function(){
  //stuff
});

Now, with $(document).on it seems I would need to do this:

$(document).on("click","#element_id",function(){
  //stuff
}).on("mouseover","#element_id",function(){
  //stuff
}).on("mouseout","#element_id",function(){
  //stuff
});

This is less concise and repeats the element. Is there an obviously simpler way to achieve this?

like image 339
joshuahedlund Avatar asked Feb 06 '13 22:02

joshuahedlund


People also ask

Can we use two events together in jQuery?

The jQuery . on() can attach multiple events on an element. In the below code I have attached 2 events to the p element. So when the element is clicked or mouse leaves this element, you will get alert box displayed.

Can multiple event handlers be added to a single element?

You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements.

How do I pass multiple events in JavaScript?

JQuery's bind allows multiple events, like so: $(window). bind('mousemove touchmove', function(e) { //do something; });

Which of the following methods helps us to attach one or more event handlers to a selected element?

The mouseenter() Method The jQuery mouseenter() method attach an event handler function to the selected elements that is executed when the mouse enters an element.


2 Answers

$(document).on({
    click: function () {},
    mouseover: function () {},
    mouseout: function () {}
}, '#element_id');

Beware of using document; you may want to use a more specific selector. Also I wouldn't necessarily say it's bad practice to have an ID element loaded dynamically, but it looks suspicious.

like image 100
Explosion Pills Avatar answered Oct 10 '22 03:10

Explosion Pills


I find this approach useful if your callbacks need to share code:

var handler = function ( event ) {

    var $target = $( event.target );

    if ( $target.is( '#element_id' ) ) }

        switch ( event.type ) {
            case 'click':
                // stuff
            break;
            case 'mouseenter':
                // stuff
            break;
            case 'mouseleve':
                // stuff
            break;
        }

    }

};

$( document ).on({
    click: handler,
    mouseenter: handler,
    mouseleave: handler,
});
like image 4
whitneyit Avatar answered Oct 10 '22 04:10

whitneyit