laggingreflex
laggingreflex

Reputation: 34627

Re-appending input element makes its events not fire

I've got an input and an event handler attached to it

var input = $(document.createElement('input'));
input.on('keypress', function (e) {
    alert('You pressed ' + e.which);
});

I append it to a div and all works fine.

$('div').append(input);

But then when I remove it and then re-append it,

$('div').html('removed')
$('div').append(input);

my event handler attached to the input doesn't work! Why and how to fix it?

http://jsfiddle.net/laggingreflex/35p2hg2h/

Upvotes: 0

Views: 24

Answers (1)

Matt Burland
Matt Burland

Reputation: 45135

Don't just remove your element by blanking the html. Use .detach and the events will be preserved:

http://jsfiddle.net/35p2hg2h/1/

input.detach();     // preserves the event handlers
$('div').html('Input removed. wait for it...')
setTimeout(function () {
    $('div').html('Input appended again, but now events dont fire :?') // actually, now
                                                                       // they will
    $('div').append(input);
}, 1000);

See also:

Differences between detach(), hide() and remove() - jQuery

Upvotes: 1

Related Questions