ITWorker
ITWorker

Reputation: 995

Catching focus on a jQueryUI menu item with a listener broader than a click listener

I've defined a jQueryUI menu with id leftmenu and on its list elements, I have defined a function on clicking one item, as follows:

$('#leftmenu>li').click(function () {
    var clickedId = this.id;
    $.ajax({
        type: "POST",
        cache: false,
        url: "/Session/Index/",
        success: function (result) {
            if (result.length > 0)
            {

                performListItemAction(clickedId);
            }
            else
            {

                window.location.href = '/Home/Index/'
            }
        }
    });
});

This works fine, but now I want to change it so that instead of the click on the menu item, I want to capture focus and selection on that item in a more general way, such as using the keyboard. Currently, I can navigate through the menu using the up and down keys on the keyboard, but the inner code does not get called. I know this is because it is only supposed to happen on click, but the same thing happpened when I tried activate and focus in place of the click as well.

How can I get it to perform the same behavior as click in a more general way that captures selection and enter of the menu item?

Thank you.

Upvotes: 0

Views: 58

Answers (1)

Twisty
Twisty

Reputation: 30893

This should be done in the select event. This way it catches both click or select from focused keyboard actions.

Example: https://jsfiddle.net/Twisty/v671x6ns/

jQuery

$(function() {
  $('#leftmenu').menu({
    select: function(e, ui) {
      var selectId = ui.item.attr("id");
      $.ajax({
        type: "POST",
        cache: false,
        url: "/Session/Index/",
        success: function(result) {
          if (result.length > 0) {
            performListItemAction(selectId);
          } else {
            window.location.href = '/Home/Index/'
          }
        }
      });
      console.log(e.type + " event, ID: " + selectId);
    }
  });
});

Upvotes: 1

Related Questions