Either newbie or experienced developer, everyone occasionally stuck with a situation that it’s event binding runs in a loop or multiple times and it runs unexpected and we are unable to find the bug because we bind the event only one time but in practical it binds so multiple times.
So for proper functioning of the events, we need to prevent binding of events multiple times in jQuery. It is very simple, just we need to unbind that event before its binding so that if it is binded before then it will be unbinded .
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | jQuery(document).ready(function(){ function setClick() { jQuery('a.trig').on('click',function(){ // write process here like toggle etc // some resizing code }) } setClick(); $(window).resize(setClcik); }) |
This code snippet will create the unexpected result but by adding single line of code, we can resolve this problem.
1 | jQuery('a.trig').off('click'); |
We unbind the event before its binding like :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | jQuery(document).ready(function(){ function setClick() {\ jQuery('a.trig').off('click'); jQuery('a.trig').on('click',function(){ // write process here like toggle etc // some resizing code }) } setClick(); $(window).resize(setClcik); }) |