Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple event handlers on dynamic content with .on()

Tags:

jquery

We can attach multiple events to an element using .on()

$('.foo').on({
    'click':function(e){
        // do stuff
    },
    'mouseenter':function(e){
        // do some other stuff
    },
    'mouseleave':function(e){
        // do completely different stuff
    }
});

We can also attach a handler to the document and filter for our elements to have the event on subsequently created elements

$(document).on('click', '.foo', function(e){
    // do stuff
});

Is it possible to combine these behaviours to bind multiple events to an element and future elements?

like image 550
Demnogonis Avatar asked Mar 10 '23 17:03

Demnogonis


2 Answers

Yes;

$(document).on({
    'click':function(e){
        // do stuff
    },
    'mouseenter':function(e){
        // do some other stuff
    },
    'mouseleave':function(e){
        // do completely different stuff
    }
}, '.foo');

https://jsfiddle.net/ktybjprh/

This is covered by the .on( events [, selector ] [, data ] ) signature, available as of jQuery 1.7

like image 86
Matt Avatar answered Apr 27 '23 03:04

Matt


You can try like this

$(document).on({
    click: function() {
        alert("click")
    },
    mouseenter: function() {
        alert("mouseenter")
    },
    mouseleave: function() {
        alert("mouseleave")
    }
}, ".foo");
<div class="foo">test</div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
like image 43
Bharat Avatar answered Apr 27 '23 04:04

Bharat