Search code examples
jquerylive

How to avoid multiple occurrences on an object?


I can never get this right - how to avoid multiple occurrences on an object. For instance, I have this function where you can click a link (go to the top), then the document will be scrolled up to the top.

this.scrollTop = function(){
    $('a[href=#top]').live('click',function(){
        alert('1');
        $('html, body').animate({scrollTop:0}, 'slow');
        return false;
    });
} 

The problem is I have an ajax page to be loaded into the same page, and the ajax page has another link (go to the top) as well, so I have to attach that scrollTop function again after the ajax call.

Then the existing link (go to the top) will occur twice when I check with the alert - how can I fix it?

  1. the scrolltop plugin.
  2. the plugin to load an ajax page.
  3. the live example.

If you click the first test thumbnail image on the left to load the ajax page, then you go to the bottom of the document to click go to the top, then you see it alert twice or more depends how many times you call the ajax page.


Solution

  • When you use live, you don't have to attach handlers anymore. From the documentation:

    Attach a handler to the event for all elements which match the current selector, now and in the future.

    Just place

    $('a[href=#top]').live('click',function(){
        $('html, body').animate({scrollTop:0}, 'slow');
        return false;
    });
    

    in your main file.

    The event handler is attached to the root of the DOM. It listens to all click events. Whenever an element is clicked that matches the selector (a[href=#top]), the handler is executed.


    Here is a very simplistic example. You will see that $('div').live(...) is only called once but the handler will be called for every element you add later.


    Update:

    How about giving the "go to top" links in the articles a different href?

    $('a[href=#article]').live('click',function(){
        $('html, body').animate({scrollTop:100}, 'slow');
        return false;
    });
    

    and use #top only for the main one. In this you don't have to use live anymore I think, you can attach the handler directly:

    $('a[href=#top]').click(function(){
        $('html, body').animate({scrollTop:0}, 'slow');
        return false;
    });