user1144510
user1144510

Reputation:

jQuery Keypress Conflict

I've built a little app that pastes some user generated text in to a textarea via a drop in div. This is done with the .click function and the .keypress function (using the Enter key).

Is there a way to get the .keypress function to fire only when the div is displayed?

Demo: http://jsfiddle.net/Mobius1/Sjyeh/2/


EDIT:

Now working!

Updated with Rory McCrossan's input: http://jsfiddle.net/Mobius1/Sjyeh/8/

Upvotes: 1

Views: 471

Answers (3)

Rory McCrossan
Rory McCrossan

Reputation: 337560

If I've understood your question, you can just check to see if the .slidebox div is visible in the keypress() handler:

$(document).keypress(function(e) {
    if (e.keyCode == 13 && $(".slideBox").is(":visible")) {
        $("#dimBackgrnd").hide().fadeOut("slow");

        $("#slide").hide("drop", {
            direction: "down"
        }, 500);
    }
});

Updated fiddle

Upvotes: 1

veeTrain
veeTrain

Reputation: 2915

Visibility is the answer you're looking for. I've updated your jsfiddle to display a possibility. Here is the code:

$(document).keypress(function(e) {
    if ($("#slide:visible").size() > 0) {
        if (e.keyCode == 13) {

            $("#dimBackgrnd").hide().fadeOut("slow");

            $("#slide").hide("drop", {
                direction: "down"
            }, 500);
        }
    }
});

Upvotes: 0

Petah
Petah

Reputation: 46050

You could check if the element is visible in the event handler:

if ($(this).is(':visible')) {
    doMyAction();
}

Upvotes: 0

Related Questions