Search code examples
javascriptjquerysyntaxjquery-on

How can I write this jquery on() the correct way?


Here is what I have

$('.test').on({
    'click', 'a', function(event) {
        event.stopPropagation();

        if( $(this).hasClass('selector') ) {
        }
        if( $(this).hasClass('prev') ) {
        }
        if( $(this).hasClass('next') ) {
        }
        return false;
    },
    mouseenter: function(){
    },
    mouseleave: function(){
    }
});

I know this is the wrong syntax, so what is the right syntax? I know I can write it if I separated the click and mouse events. But is there a way to combine them or do I need to separate them? Thanks for your time


Solution

  • You have to make 2 separate calls if you don't wish to use the same selector in both:

    $('.test').on({
        mouseenter: function() {},
        mouseleave: function() {} //null selector/no selector here so these events only fire on `.test` itself
    }).on("click", "a", function(event) { //Selector here so this event only fires for `a` descendants of `.test`
        event.stopPropagation();
        if ($(this).hasClass('selector')) {}
        if ($(this).hasClass('prev')) {}
        if ($(this).hasClass('next')) {}
        return false;
    });
    

    You also forgot to specify the event parameter, which would have caused a bug in IE and firefox