views:

810

answers:

1

I'm trying to load all my website pages using jQuery .load method so, thats how my website looks:

<script type="text/javascript">  
  $(function() {
    $('.link').bind('click', function(e) {
            var page = $(this).attr('href');
            $('#site').addClass('loading');
            $('#content').load(page, function (){
            $('#site').removeClass('loading');
    });

    e.preventDefault();
    return false;
  });

<a href="test.php" class="link">Test</a>

With this code, every link that gets class="link" will load my page on the div #content. Works fine! No problems but when I load the test.php, if i use the class="link" on any link, or button, or whatever, it just does not work and the new page is loaded outside my #content.

Already tried to copy this to the new-loaded file and it doesn't work, anyone got a hint?

Thanks

+2  A: 

This is because when you bind an event it only binds it to the elements that are in the DOM at that time. So if you add new ones later on they won't be bound to the event you previously attached. Assuming you have jQuery 1.3, it has a built-in function to get around this called live. With it, you can bind an event to all current and future elements. It doesn't support all events, but click it does support.

So keeping that in mind, you just have to replace this:

$('.link').bind('click', function(e) {

With this:

$('a.link').live('click', function(e) {

(I added the a. to the selector because it is much more efficient to specify the tag if at all possible)

If you don't have jQuery 1.3, you should upgrade as soon as possible. If you can't, check out the livequery plugin which achieves the same thing but in a much less elegant way. Alternatively, you can simply have a function to bind the action and call it everytime you load new data in. All things considered, however, jQuery's live is the best way to do this.

Paolo Bergantino
I also wrote a plugin called bond which works like live if you will be needing 'focus' and 'blur' live functionality. http://code.google.com/p/jquery-plugin-dev/source/browse/trunk/jquery.bond.js
Tres
Looks ok but still, it does not work with buttons, and i Need to send POST data using my new test.php page, any other hint?Thanks