0

I have an element that has a href attribute calling a javascript function. This element is in two classes : ( class="icon32 icon-close" ). This link is represented as an "X" on a div that has the class .modal and is used to close the div. My question is, can I make the div close, therefore, calling the a link, when the user presses the "esc" key. I tried the code below, but it does NOT work, although the alert shows up:

$(document).keypress(function (e) {
    if (e.keyCode == 27) {
        alert('esc was pressed');

        $('.modal>.icon32').click();
    }
});
7
  • but it does work ?? or it doesn't work.. Commented Jan 17, 2013 at 10:08
  • 1
    Shouldn't jQuery UI Dialog already take care of handling the Esc? Commented Jan 17, 2013 at 10:08
  • Let's see the relevant HTML and JavaScript for the <a> tag. Commented Jan 17, 2013 at 10:08
  • Try to use keydown instead of keypress Commented Jan 17, 2013 at 10:09
  • try $('div.modal .icon32').click(); Commented Jan 17, 2013 at 10:11

5 Answers 5

2

You should be calling the .click() event of the native DOM element not the jQuery .click() event. To do that, have such code instead:

$('.modal>.icon32')[0].click();
Sign up to request clarification or add additional context in comments.

Comments

0

which doesn't work - pressing the esc key (in which case try using e.which instead of keyCode), or the actual selector to invoke the click? (in which case, test if your selector is wrong by giving the element an explicit ID and try selecting it that way to verfy that it's just your selector).

Also, why do you need to "click" the "X" ->Can you not just "hide()" the modal div element?

Comments

0

You can also do this :

$(document).keyup(function (e) {
    if (e.keyCode == 27) {
        // As soon as he escape is clicked you do..
        $('.icon32.icon-close').click();
    }
});

Comments

0

You'll need to use keyup or keydown for the escape key, and e.which is normalized in jQuery:

$(function() {
    $(document).on('keyup', function (e) {
        if (e.which == 27) {
            $('.modal > .icon32').trigger('click'); //NOTE: direct child selector
        }
    });
});

FIDDLE

Comments

0

If you are using jQuery modal dialog, use option closeOnEscape: false like this:

$("#div").dialog({
            modal: true,
            resizable: false,
            closeOnEscape: false,
                buttons: {
                    Ok: function () {
                       //do something
                    }
                    Cancel: function(){
                       //do something
                    }
                }
            });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.