tags:

views:

467

answers:

3

I have HTML input and button elements. I use the buttons to submit forms, open secondary windows, etc. The problem is, a single click is turning into 2 (and sometimes many more) form submissions, or opening two additional browser windows. I've reproduced the problem in multiple web browsers. I've tried switching jQuery versions and that didn't change anything. What could be causing this sort of thing to happen?

+1  A: 

Given that you have not supplied a lot of information, the best I can recommend is looking at one()

http://api.jquery.com/one/

jarrett
This worked for me when the accepted answer didn't, +1
t_scho
+1  A: 

Your problem may be happening because you are assigning the same handler to the click event multiple times. I suggest you check that the line where you assign the handler is not being called multiple times inadvertently. Another solution could be a call to unbind first like this:

$("#myButton").unbind("click").click(myHandler);

But without seeing some code I'm just guessing.

Darko Z
That was the problem. Thanks.
gholmes
A: 

jQuery Sparkle provides a clean elegant solution for this, by calling the function "once" you can bind a handler to an event only once.

It is an important improvement over Darko Z's suggestion as using:

$("#myButton").unbind("click").click(myHandler);

Would unbind any other "click" handlers associated to the "click" event each time it is called. So you sure do ensure it is only binded once, however you unbind everything else accidentally! Ooops!

jarrett's suggestion unbinds the "click" handler right after it is called, so if you would to have the handler called again (after it's initial fire) you would have to rebind the handler.

Using jQuery Sparkle's once will allow the handler to fire as many times as it needs, but to only be binded once instead of multiple times. You can use it like this:

$('#myButton').once('click', function(){
    // my handler
});

Or if you would like to support data in your callback just like jQuery's built in "bind", then you can use:

$('#myButton').once('click', data, function(){
    // my handler
});

You can find the source code for defining the once function right here: http://bit.ly/a5cyNV

It's open source under the AGPL licence, so you can feel free to grab what you need out of it worry free! :-) It's also actively developed on a day to day basis so you will never be short on support.

But most importantly it is a DRY Plugin/Effect Framework to allow you to develop plugins and extensions much more easily. So hope this helps to achieve that goal!

You can find more about jQuery Sparkle, and see some demos of it right here at it's homepage: http://www.balupton.com/projects/jquery-sparkle

Hope I've helped!

balupton