Close dropdown with ESC key

Asked

Viewed 313 times

1

It would be possible to make the dropdown below, close with the ESC key?

$("#jq-dropdown-1").on("contextmenu", function(event){
    event.stopPropagation();
    
    var a = $("a[data-jq-dropdown='#jq-dropdown-1']");
    
    if(!$(a).hasClass("jq-dropdown-open")){
      $(this).toggle();
      $(a).toggleClass("jq-dropdown-open");
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<link href="https://labs.abeautifulsite.net/jquery-dropdown/jquery.dropdown.min.css" rel="stylesheet"/>
<script src="https://labs.abeautifulsite.net/jquery-dropdown/jquery.dropdown.min.js"></script>

<a href="#" data-jq-dropdown="#jq-dropdown-1">Dropdown</a>
<div id="jq-dropdown-1" class="jq-dropdown jq-dropdown-tip">
    <ul class="jq-dropdown-menu">
        <li><a href="#">Science</a></li>
        <li><a href="#">Eletronics</a></li>
        <li><a href="#">Pellentesque convallis enim.</a></li>
        <li><a href="#">Internet</a></li>
        <li><a href="#">Business</a></li>
    </ul>
</div>

1 answer

2


Using an event with keyCode:

$(window).on('keypress',function(event){
    if(event.keyCode==27){
        $("#jq-dropdown-1").toggle();
    }
});
  • 1

    Like, but using the toggle, when pricing "Esc" again was to open the Dropdown.

  • 1

    True, I hadn’t thought of it, but nothing like a if() to check if the dropdown is open does not solve

Browser other questions tagged

You are not signed in. Login or sign up in order to post.