PHP Coding Tips

Wednesday, August 8, 2012

jQuery action called twice or more times

If you are begginer in jQuery you can do a common mistake, espacially when dealing with dynamic content, ajax, and dynamic interactive elements. This problem can be non-working action that you have bind to some element (but really did not) or action is evaluated multiple times. To deal with that problem, you must understand how jQuery works. When you add action like .click(function(){....}); you are binding this action only in time when this element exists, so if you provide new element in for exaple AJAX request, it will not react to click. You must bind this event after adding element to DOM structure by calling .click with its selector. Another common problem is that function can be called multiple times. This works this way, because you are binding function to element multiple times. Each time witch executing .click(function(){});. You can clear previously assigned action to that element and call click() to assign fresh, single event listener, like that:$("#mybutton").unbind('click'); $("#mybutton").click(function(){ alert('x'); });But be carefull, you can detach some earlier bind to other actions you have binded !

15 comments: