peter
peter

Reputation: 153

jquery click a link

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();
    }
});

Upvotes: 0

Views: 219

Answers (5)

Prasanth
Prasanth

Reputation: 3041

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
                    }
                }
            });

Upvotes: 0

Shadow Wizzard
Shadow Wizzard

Reputation: 66398

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();

Upvotes: 2

adeneo
adeneo

Reputation: 318342

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

Upvotes: 0

insomiac
insomiac

Reputation: 5664

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();
    }
});

Upvotes: 0

Stephen Byrne
Stephen Byrne

Reputation: 7505

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?

Upvotes: 0

Related Questions