1

My HTML looks like this

<div id="current">&nbsp;</div>

<div class="data1">
  <div class="foo"><p>Some Text</p></div>
</div>

<span onclick="replace()">Click to replace div</span>

My JQuery/javascript is like this

$(document).ready(function() {
  $('.foo').click(function() {
    alert('worked');
  })
})

function replace() {
   $('#current').html($('.data1').html());
}

The alert triggers fine on the .foo class within the .data1 div but after replacing the contents of #current with .data1, the onclick event doesn't trigger on the .foo class within the first div.

What am I missing? Any help would be appreciated!

2 Answers 2

3

Using .html() will create new HTML element but the event will not follow. You need to append a DOM element. The DOM element should be a clone of the original:

$('#current').empty().append($('.data1').clone(true));
Sign up to request clarification or add additional context in comments.

3 Comments

This is exactly the same as $('#current').html($('.data1').html());
@AndreasFurster the difference to note is that one inserts a HTML String and the other one a DOM element with the handlers.
@AndreasFurster no its not, .html() take the text content. This mean that the event will not follow. append will use the DOM element itself with all the data that come with it. Using clone will duplicate the element instead of moving it and passing true as parameter mean it's passing the Event data of the element and all its childrens.
1

Since you're dynamically appending the element, use event-delegation

$('div').on('click', '.foo', function() {
  alert('worked');
})

2 Comments

+1 Agreed. Event delegation is more "obvious" in what is happening and no additional coding required.
@LeeTaylor yup :) Thanks BTW

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.