gfranko / jquery.selectBoxIt.js

A jQuery Select Box Plugin for Mobile, Tablet, and Desktop
http://www.selectboxit.com
MIT License
852 stars 301 forks source link

keypress 'esc' event is never released when the focus is on a SelectBoxIt #333

Open juampi92 opened 9 years ago

juampi92 commented 9 years ago

The thing is, almost every select on the app I'm developing is inside a popup. And to close the popups we use the escape key.

When the focus is in a select and we use the escape key, it will close the dropdown, but now we have the esc blocked unless we take the focus away from the the select, and this prevents us from closing the popup.

The exact problem this line

if(keydownMethod && currentKey !== "tab") {
    e.preventDefault();
}

This line always prevents the esc key from being triggered, so this is the solution I came up with:

Fist, tell when the user presses the esc key but the dropdown is already hidden, so in this method would be

"esc": function() {
    // If the dropdown is already hidden, let the event flow
    if (!self.list.is(":visible")) {
        return true;
    }
    // Closes the dropdown options list
    self.close();
}

So now if the dropdown is not visible, returns true. And to handle this event, we'd change the keydown event for:

"keydown.selectBoxIt": function(e) {
  // Stores the `keycode` value in a local variable
  var currentKey = self._keyMappings[e.keyCode],
    keydownMethod = self._keydownMethods()[currentKey],
    // When true, avoids the preventDefault
    resultAvoidPrevention = false;

  if (keydownMethod) {
    resultAvoidPrevention = keydownMethod();
    if (self.options["keydownOpen"] && (currentKey === "up" || currentKey === "down")) {
      self.open();
    }
  }
  if (keydownMethod && currentKey !== "tab" && resultAvoidPrevention !== true) {
    e.preventDefault();
  }
},

Notice the resultAvoidPrevention variable that turns true if the esc event returned true, and that makes the e.preventDefault() line be skipped.

--- Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/16528807-keypress-esc-event-is-never-released-when-the-focus-is-on-a-selectboxit?utm_campaign=plugin&utm_content=tracker%2F23157&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F23157&utm_medium=issues&utm_source=github).