Thursday, June 6, 2024
 Popular · Latest · Hot · Upcoming
54
rated 0 times [  60] [ 6]  / answers: 1 / hits: 28371  / 10 Years ago, thu, may 15, 2014, 12:00:00

I have a checkout form that uses php to load some javascript & html into #Div-A when the page loads. The javascript binds a click event to #Button-A in the same div. Something like this:



<div id=#Div-A><input type=button id=Button-A/>
<script type=text/javascript>
$('#Button-A').bind('click', function() {
$.ajax({
type: 'get',
url: 'some/url/gets/called',
success: function() { this happens on success }
});
});</script>
</div>


Afterward, #Global-Button is created and a javascript function binds a different click event to this second button which then triggers #Button-A to be clicked like this:



$('#Global-Button').live('click', function(event) {
$(#Button-A).trigger(click);
})


The reason being that the contents of #Div-A can change (via ajax), so the second button acts as a global trigger regardless of which button or function happens to reside in #Div-A.



The problem I'm encountering is that for some reason if #Global-Button is clicked after page load #Button-A gets triggered twice. If an Ajax event reloads the contents of #Div-A then all is well and the the trigger happens only once as it should.



I've examined the html within #Div-A before and after reloading via Ajax and everything appears to be identical. There are definitely no duplicate buttons or functions anywhere as far as I can see that would cause two events to be triggered.



I know only a very little about the DOM and can only guess this has something to do with the order in which things are loaded and events are bound.


More From » jquery

 Answers
5

This is always recommended to use 'unbind' before bind to make sure the event is not bound multiple times. In your case, there may be two possibilities -




  1. '#Global-Button' click function is bound twice.

  2. '#Button-A' click function is bound twice and '#Global-Button' is actually triggering the click once.



Change your code like -



$('#Global-Button').unbind('click').bind('click', function(event) {
$(#Button-A).trigger(click);
})


and also -



$('#Button-A').unbind('click').bind('click', function() {
$.ajax({
type: 'get',
url: 'some/url/gets/called',
success: function() { this happens on success }
});
});

[#71001] Tuesday, May 13, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
madalynn

Total Points: 342
Total Questions: 95
Total Answers: 106

Location: Turkmenistan
Member since Sat, Apr 16, 2022
2 Years ago
;