Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery multiple click event

I'm forced to use a script loaded from an external server.

This script basically adds an element <div class="myClass"> and bind a click method to it.

The thing is, in the click function associated to the element, they have a return false statement at the end.

I also have my own script and I'm trying to add a click method to the same element using $(document).on('click', '.myClass', function() { ... })

My problem is that their event is triggered before and the return false in their function doesn't trigger my own click method.

I've tried loading my script before theirs but that didn't fix the problem. I've read about unbinding and then rebinding but I'm not sure it's a good option since their code can change at any moment.

Anything else I could try?

like image 749
VVV Avatar asked Sep 06 '13 03:09

VVV


People also ask

Why is this jQuery Ajax click event firing multiple times?

an Event will fire multiple time when it is registered multiple times (even if to the same handler).

How do I pass multiple events in JavaScript?

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


2 Answers

You need to make your handler function return false.. it prevents the event from bubbling.

In your tag html you have to write something like:

<button type="button" class="btn" onclick="myHandler(); return false;"></button>

Or if you use jQuery:

$(".btn").on('click', function (event){ 
    //do stuff..
    return false;
});
like image 128
andrea.rinaldi Avatar answered Sep 28 '22 19:09

andrea.rinaldi


The problem is that event delegation depends on the event bubbling up to the element that you bind the handler to. When their handler returns false, that prevents bubbling.

You'll have to bind the handler directly to the elements after they're added:

$(".myClass").click(function() { ... });
like image 22
Barmar Avatar answered Sep 28 '22 18:09

Barmar