views:

27

answers:

3

I have a number of jQuery scripts that select elements within the area that I run a partial page refresh on.

I am using this css tricks code snippet to refresh that part of the page:

$('#refreshbutton').click(function() {

 var url = "http://myUrl.com/indexTest.php?ID=" + Math.random(); 

 setTimeout(function() {
        $("#maindisplay").load(url+" #maindisplay>*","");
 }, 100); 
});

The problem is that the elements within #maindisplay are changed, thus are considered new elements in the dom. Since the scripts that select those elements and attach functions to them run at domready and not during the partial refresh, this poses a problem.

So far I have been unable to find a way to reattach the scripts to the elements within #maindisplay after I partially refresh it.

My question is: What is the optimal way to reattach the scripts to the refreshed area of the page.

Thank you for any advice.

A: 

Does load() not take a callback function as it's second argument? Why not reattach event handlers to the elements with that function?

$('#result').load('ajax/test.html', function() {
  //reattach event handlers here.
});
akellehe
+1  A: 

You need to use the live() function to attach your click handler.

rhesus
A: 

You have the following options that I can think of:

  • Put the attach in a function and call that function on page refresh
  • Use the .live() functionality
  • Use .delegate() functionality
  • Put the Javascript reference to the functionality in a reference in the refresh so that it executes as a part of that refresh
  • Put the function in the callback
  • make it part of your setTimeout
  • some other creative method I did not think of...

Just a note: I would look at the .delegate() with contextual selection added in recent versions (available in 1.4.2 for instance).

Mark Schultheiss
Thank you for your answer, as a quick follow up question. One of the scripts attached to the elements is a .tooltip function, the function fires on mouseenter. Now, if I set it up like this: $("body").delegate(".tool", "mouseenter", function(){ $(this).tooltip({//Things });});Then the user has to first mouse over the element, then mouse over again to get the tooltip. How can use .delegate or .live without having them mousing over twice?
BorisKourt
I think this has to do with the binding level. Look at chaining in .delegate and consider the mouse event, which you want to keep as local as possible so it fires on the right element and not on the parent element. Keep in mind with .delegate, you can chain whereas .live cannot. You can see a blog on it here:http://brandonaaron.net/blog/2010/03/4/event-delegation-with-jquery
Mark Schultheiss
Thank you Mark, this was very helpful.
BorisKourt