2

I have a JQuery UI menu on my page. I want to alter the default behavior of when an item is selected, so that instead of following the link, my function is just executed. The following works:

$mymenu.find("a").click(function(){
    return false;
});

However, it prevents the 'select' event in the menu from executing. If I remove it, the 'select' event triggers, something like

$mymenu.menu({
    select: function(event, ui) {
        alert(ui.item.text());
    }
});

However, neither event.preventDefault() or event.stopPropagation() stops the link from being followed. The following stops the link from being followed, but gives me the same problem of the 'select' event not being triggered.

 $mymenu.find("a").click(function(e){
     e.stopPropagation();
 });

How would I go about preventing the link from being followed but still trigger the 'select' event?

Ford
  • 2,559
  • 1
  • 22
  • 27
  • You want to use preventDefault() and it has to work. Can you replicate it in a fiddle? Here is a fiddle where it works. http://jsfiddle.net/a6YWe/. Using preventPropagation obviously is wrong as it will prevent it from being bubbled up and will not reach your select event. – PSL Jun 18 '13 at 00:09

1 Answers1

1

If I'm interpreting your question correctly, maybe this is what you're after:

Put your event handling code inside the click event for the menu item, and call preventDefault() at the end of that click event. You won't need both the click handler and the select: handler.

$mymenu.find("a").click(function(event){
    // event handling code - alert($(event.target).text());
    event.preventDefault();
});

Anything you want to run on the click will still run, but the link will not be followed.

bbill
  • 2,264
  • 1
  • 22
  • 28
  • Okay, so I figured it out, this *DOES* work, but I have to specify $mymenu.find("li"), I'm not exactly certain why, would you know? – Ford Jun 18 '13 at 00:31
  • Scratch that, it's triggering an error which is preventing the anchor from activating...lol.. – Ford Jun 18 '13 at 00:44
  • You were right in your first comment, since you're selecting the parent and finding all 'li' elements that are its children. I've found Firebug in Firefox and Chrome's debugger to be really helpful for errors like the one it seems you caught in your second comment. Edit: it would be great if you could mark this as the answer if you've solved your problem. :) – bbill Jun 18 '13 at 05:59