Double-linked jQuery event

I have two html pages: one index.html and groups.html each page as ul> li> a . with different class names.

I place click events in a separate js file as follows:

 // Index Page Onclick events $('body').on('click','.menuClass',function(e) { e.preventDefault(); var menuid = $(this).attr('id'); alert(menuid); }); // click on groups html >> this page alert fires twice $('body').on('click','.grpClass',function(e) { e.preventDefault(); var menuid = $(this).attr('id'); alert(menuid); }); 

the script file is loaded into both html files, the second function for groups.html fires the click event twice.

Is there a way to avoid this or a better way to achieve the same?

+6
source share
1 answer

Use stopImmediatePropagation() , this will stop the event from bubbling through the DOM of your page:

 // Index Page Onclick events $('body').on('click','.menuClass',function(e) { e.preventDefault(); var menuid = $(this).attr('id'); alert(menuid); }); // click on groups html >> this page alert fires twice $('body').on('click','.grpClass',function(e) { e.preventDefault(); e.stopImmediatePropagation(); var menuid = $(this).attr('id'); alert(menuid); }); 

Here is an example of how this works: JSFIDDLE . If you press test1 , bubbling will be prevented and only one warning will be shown. If you press test2 , the event will not be stopped, and you will receive two warnings.

+20
source

All Articles