Attach multiple events to same elements

Need to attach multiple events to same elemnt which needs to perform multiple actions, tried in the below way did’t get wat’s in the below code the ‘hover’ is not working

$(document).on('click', '.testdiv', function() {
    //some task will goes here  
    $(this).unbind('hover');            
}).hover(function() {
    $(this).find('.myBtn').css('background','#666666');
});

This doesn’t work because in the first handler this refers the the .testdiv element, while in the second one this refers to document; so you’re actually attaching event listeners to different elements, only that the first one is delegated. That said, chaining event listeners is perfectly possible in jQuery; another possibility would be using the object syntax, like e.g.

$('.testdiv').on({

  'click': function() {
    $(this).off('mouseenter');
  },

  'mouseenter mouseleave': function() {
    console.log(this);
  }
});

See the API documentation for details.

1 Like

Kudos to you!!! and thanks for the explanation.

One more question how can we handle with dynamic elements means I have used $(document) because of event delegation, because the ‘.testdiv’ is dynamically loading, to attach an event handler I am referring to the document object, otherwise event handler which is attaching to ‘.testdiv’ like you had written it is not working.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.