6

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

I have place the click events in a seperate js file as following :

// 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 in both the html files the second function for groups.html fires the click event twice.

Is there any way to avoid it or any better way to achieve the same?

3
  • have you tried to combine those 2 selectors into 1, since they essentially do the same at the moment? are you using AJAXed navigation or non-AJAXed one? Commented Aug 21, 2012 at 9:43
  • also, you might want to bind to vclick if you're using jQuery Mobile, since that is a standardized virtual event working cross-platform, while click might not work on some platforms Commented Aug 21, 2012 at 9:44
  • @ZathrusWriter : Thanks for vlick i understand that i can use selector but eventually there will be n pages so giving me n selectors .. looking for an elegant way to achieve the same. Commented Aug 21, 2012 at 9:47

1 Answer 1

20

Use stopImmediatePropagation(), it 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 click test1, the bubbling is prevented and only one alert is shown. If you click test2, the event is not stopped and you will get two alerts.

Sign up to request clarification or add additional context in comments.

1 Comment

ha :) perfect I say :) ..Thank you!!1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.