4

I'm displaying a tabbed interface with the help of jQuery. When you click a tab, a ajax call will replace all html from a $(".content") element with new html, using something like

$(".content").html(response);

When I do this, are all jquery events and functions that are attached to elements inside the .content div removed? Is it ok to fire these events and functions again after I replace the HTML ? If I click the tabs 324523452354 times, will it duplicate jQuery data every time?

1
  • 1
    Data and event handlers are attached to elements. When the elements are removed, the handlers etc are removed too. How can it work when the elements they are assigned to don't exist anymore? Commented May 3, 2011 at 18:56

3 Answers 3

2

Yes. They will be removed. You can use the live event to attach to elements that dont exist yet.

 $(".myElementClass").live("click", function (e) {
         e.preventDefault();
         //do stuff
});

In this case, this function will always be called on myElement no matter when it is injected into the DOM.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 but in this case you wouldn't want to bind to an ID, but a class since ID's are supposed to be unique. Another good method would be delegate()
Ya, it was just an example of live. I have updated my answer.
0

All HTML inside of your selector is replaced with the parameter you pass in, implying it is completely removed from the DOM. Meaning if you have:

<div id="mine">
  <ul>
    <li>One thing</li>
  </ul>
</div>

And I do a call as such:

$('div#mine').html("hey");

My HTML will then be:

<div id="mine">
  hey
</div>

As you can see the is completely removed and all its bound events mean nothing. If you use the jQuery.live() binding instead however, then elements that don't yet exist can have events associated with them. Meaning if you add some elements to the DOM then they events will still work, without you have to rebind if you add more, or replace them.

Comments

0

**.live** events are binded at the document level , read the following document which is really useful

http://www.bennadel.com/blog/1751-jQuery-Live-Method-And-Event-Bubbling.htm

1 Comment

Can you post a synopsis of the document you are linking to?

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.