clarkk
clarkk

Reputation: 1

How to empty() element but keep event handlers etc?

How can you empty an element and re-use the elements and keep event handlers etc.?

http://jsfiddle.net/WrMbG/

<div></div>

var inp = $('<input type="text" />')
    .keydown(function(){
        alert('keydown');
    });

$('div').append(inp);
$('div').empty();
$('div').append(inp);

all event handlers and etc. is destroyed when you empty an element.. how can you avoid this?

Upvotes: 2

Views: 1207

Answers (5)

Adam Bailin
Adam Bailin

Reputation: 552

Try using jQuery.live(), which searches for newly created elements (whereas keydown will just try elements that were created before the keydown handler was created).

<div></div>

var inp = $('<input type="text" />');

// edit: live won't work when chaining it, so attaching separately
$("input").live('keydown', function(){
    alert('keydown');
});

$('div').append(inp);
$('div').empty();
$('div').append(inp);

See here for more info.

Upvotes: -1

Shalom Sam
Shalom Sam

Reputation: 1559

try .detach() -

$('div input[type="text"]').detach();

Upvotes: 0

Herohtar
Herohtar

Reputation: 5613

You might try using .live()

var inp = $('<input type="text" id="myinput" />'); 

$('#myinput').live('keydown', function(){
    alert('keydown');
});

$('div').append(inp);
$('div').empty();
$('div').append(inp);

Upvotes: -1

Dan Short
Dan Short

Reputation: 9616

Try this jsfiddle

When you create your inp variable, it's a unique jQuery object. If you want to use it multiple times, you need to clone it in order to be able to reuse it. Supply the true parameter to the clone() method to get a deep copy, include events.

Upvotes: -2

Dennis
Dennis

Reputation: 32608

Use detach on the child instead:

inp.detach();

If you have multiple elements

var saved = $("div").children().detach();

From the documentation on empty:

To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.

Upvotes: 7

Related Questions