-2

Javascript below is used to close div when an ESC Key is clicked.

<script>
    $(document).keyup(function(event) {
        if(event.which === 27) {
            alert('closed now');
            $('#content').hide();
        }
    });
</script>

<div id="content">My content to be closed is here</div>

Now what I want is to close the content from a button click which will then call Esc Key javascript function

<button id="close_content">Close</button>

Thanks

bowman87
  • 93
  • 1
  • 4
  • 14
  • 3
    Possible duplicate of [Which keycode for escape key with jQuery](https://stackoverflow.com/questions/1160008/which-keycode-for-escape-key-with-jquery) – Francisco Flores Aug 28 '17 at 10:49
  • Right, and did you try anything? Where's your button code? – Mitya Aug 28 '17 at 10:50
  • A mouse is not a keyboard, a click is not a keyup, you have to see them as two seperate events. You can react to them in the same way, but you need two different event handlers. – KIKO Software Aug 28 '17 at 10:51
  • So you actually have no clue what your current script does? – Teemu Aug 28 '17 at 10:55

2 Answers2

0

Put the code in a named function, then call it from both event handlers.

$(document).ready(function () {
    function close_content() {
        alert('closed now');
        $("#content").hide();
    }

    $(document).keyup(function(event) {
        if (event.which == 27) {
            close_content();
        }
    }
    $("#close_content").click(close_content);
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Add this code in your script, when you click Close button the content "My content to be closed is here" will hide. $(document).ready(function () { $("#close_content").click(function() { $("#content").hide(); }); });

Lavanya E
  • 206
  • 2
  • 12