Jordi P.S.
Jordi P.S.

Reputation: 4018

Replace innerHTML and get back to the original one keeping the events

I have a target div el with some components displayed. These components have some events attached (on mouse over, on click). I don't control this code neither those events. They are just there. I'd like to render a widget inside this div. To do so I'm doing something like:

var save = el.innerHTML; 
el.innerHTML = "my widget code";

When my widget finishes its process I want to get back to the original content so I do:

el.innerHTML = save;

The components previously saved are correctly replaced but the events attached to them don't work anymore.

I can't hide, show divs. I need to replace the innerHTML to have the exact style and positioning.

What would you do in my case? I'm using jQuery if it helps.

Thanks.

Upvotes: 1

Views: 2785

Answers (3)

benjaminbenben
benjaminbenben

Reputation: 1228

You might find .detach useful - http://api.jquery.com/detach/

It does the same as .remove but keeps all the associated jquery element data - which will include any event listeners added with jquery, though you will lose any 'regular dom events' attached.

you'd have to re-attach the element with jQuery too:

var stored = $(el).detach();

//… wait for something to finish, then reattach

stored.appendTo('#outer');

Upvotes: 3

Felix Kling
Felix Kling

Reputation: 816522

When you serialize DOM elements back to HTML, all the event handlers and bound data are lost.

If you have DOM, work with it, not with HTML:

var save = $(el).children().detach();
$(el).html(widgetHTML);

// later
$(el).empty().append(save);

Upvotes: 5

wirey00
wirey00

Reputation: 33661

You can delegate the event to your el element since it doesn't seem to change - Those newly added elements did not exist at the time of binding

$(el).on('click','yourelementtoattachevent',function(){
       // replace click with your event/events
       // your code goes here
});

This is assuming you are using jQuery 1.7+, for others use

$(selector).live();                // jQuery 1.3+
$(document).delegate(selector, events, handler);  // jQuery 1.4.3+
$(document).on(events, selector, handler);        // jQuery 1.7+

Upvotes: 1

Related Questions