Question

I have scoured SO trying to find a solution (or piece one together), however I cannot find a definitive answer to my dilemma.

What I am attempting to do is the following:

$("#mini_search_input").keypress(function(event){

    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '13'){
        alert('my event!!');    
    }

});

Now, this snippet works great on the element if it enters the DOM at display:block;. However, when it starts at display:none; and then I use a .show() to reveal it, the keypress stops functioning. I've tested this in both Chrome and Firefox.

Is there something I am missing as to why that keypress won't bind to my element (no console errors -- just doesn't "fire") if I start the element as hidden?

Was it helpful?

Solution

Try .on()

As elements are added dynamically you can not bind events directly to them .So you have to use Event Delegation.

$(document).on('keypress', '#mini_search_input', function (event) {
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if (keycode == '13') {
        alert('my event!!');
    }
});

Syntax

$( elements ).on( events, selector, data, handler );

OTHER TIPS

Its more possible that you're not just hiding & showing the element. Because, the event would fire if the element is present in DOM even if it has display:none & then made display:block later.

You're probably dynamically populating that element. In which case, use event delegation using .on()

$(document).on('keypress', '#mini_search_input', function(event){
    //Your code
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top