Ryan Baker
Ryan Baker

Reputation: 39

Loading to a div element with jquery after it has already been loaded

I have a page which loads its inner content using jquery and a simple navigation menu. Because of this there is only one regularly accessed URL for the page. My problem is that I can't seem to get content from within the loaded div to modify 'that' particular div. For example I have something along the lines of this as my jquery loader function:

$(document).ready(function(){

// load index page when the page loads
$("#response").load("start.html");
$("#home").click(function(){
// load home page on click
    $('#response').load('start.html', function() {
        resizefunc();
    });
});
...

If I create an element within one of the loaded pages that links to # with an id from that loader function, clicking it simply moves the focus back to the top of the page rather than reloading my "response" div.

Upvotes: 1

Views: 1184

Answers (1)

hunter
hunter

Reputation: 63512

Since those navigation elements (ie #home) don't exist initially, binding those events on ready will do you no good. You'll need to live bind those same events or delegate them from a parent element.

This can easily be showcased by doing this simple test:

alert($("#home").length);

Which will alert 0


Try this solution instead

$(document).ready(function(){
    $("#response").load("start.html");
    $("#home").live("click", function(){
        $('#response').load('start.html', function() {
            resizefunc();
        });
    });
});

or

$(document).ready(function(){
    $("#response").load("start.html");
    $("#response").delegate("#home", "click", function(){
        $('#response').load('start.html', function() {
            resizefunc();
        });
    });
});

using live or delegate to bind this selector to a click rather than a regular click event will allow the assigned function to exist for all selected elements that exist now and may exist in the future.

Upvotes: 1

Related Questions