jqueryjquery-uijquery-ui-menu

JQuery UI Menu Item prevent default link behavior


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?


Solution

  • 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.