views:

367

answers:

4

Hi everybody,

I'm very new to jQuery, Ajax and things like these. I've found solutions on how to inject HTML fragments into my site:

 $(document).ready(function(){  
     $('a').click(openContent); //binding all anchors to this function
 });

function openContent(){ 
 var path = $(this).attr('href');
 $('#content').load(path); 

 return false; //to prevent browser from loading the single HTML fragment
}

That works really fine! The problem is, these function won't be executed when clicking on anchors located in the new HTML fragment which were injected right before. So the fragment won't get injected into div, the browser will only load the fragment for itself.

Hope there are solutions which aren't that tricky... thanks

sam

+4  A: 

use live, that will bind it to every anchor that gets added:

$('a').live('click',openContent);
derek
damn... this is easy and works great! Thanks man!
sam
but there are also pictures connected to the jQuery lightbox plugin (balupton-edition) with rel="lightbox-tour" in these fragments. They are displayed in new window instead of the lightbox-div.
sam
+1  A: 

Also in jQuery 1.4+ you can use
$(document).delegate('a', 'click', openContent);

*The main difference between live and delegate, live attaches events to the document and handles events once they bubble up. With delegate you can specify the context in which to attach the event to . The example here is exactly the same as using live. Now Lets say that you wanted only anchors that appeared in a div with an id of "contentArea" to load content in this manor. In this case you would write $("#contentArea").delegate('a', 'click', openContent);.

For more on the differences between live and delegate check out Quick Tip: The Difference Between Live() and Delegate()

joshatjben
This would be a more helpful answer if you explained the difference between `live` and `delegate`, especially if you included a different context than `live` uses (your code should be identical in functionality to that in derek's answer).
eyelidlessness
Great point, updated my answer
joshatjben
I tried delegate, but the fragment won't get displayed in the div box
sam
A: 

Ok, live does a good job BUT,

there are also pictures connected to the jQuery lightbox plugin (balupton-edition) with rel="lightbox-tour" in these fragments. They are displayed in new window instead of the lightbox-div. Any suggestions?

sam
A: 

So the lightbox isn't handling the dynamically loaded links? You could update your code to rerun the lightbox plugin in the load callback. Something like this:

$(document).ready(function(){  
    $('a').live('click', openContent);
});

function openContent(){ 
    var path = $(this).attr('href'),
        content = $('#content');

    // added callback here
    content.load(path, function () {
        content.lightbox();
    }); 

    return false; 
}
Andrew