AlexW.H.B.
AlexW.H.B.

Reputation: 1871

jquery function not getting called inside of an ajax function

So im trying do disable links on some <li> ellements that have been loaded in from another page using an .load() function, but for some reason i'm not able to effect those list items.

var from_post = false; 

$(document).ready(function() {
    //so this is the function that loads in data from another page
    $("#gallery").load('http://localhost/index.php/site/gallerys_avalible/ #gallerys_avalible'), function() {
        console.log('hello');
        // sense there are no other li elliments on the page i thought this
        // would be okay. but this function never gets called, i've moved it
        // all over i just recently attached it to the load function thinking
        // that maybe if the load was not complete it would not run, but i
        // have had no luck.
        $('li').click(function (e) {
            e.preventDefault();
            console.log("I have been clicked!");
            return false;
        });
    };


    $('#addNew').click(function () {
        console.log('i got called');
        $('#new_form').fadeIn(1000); 
    });

    $('form').submit(function() {

        if(from_post) {

           //submit form
            return true; 

        } else {

            //dont submit form. 
            return false; 

        }
    });

any help would be greatly appreciated, oh and the other thing is that i can run this function through firebug, and it works 100% fine. so im stumped.

Upvotes: 0

Views: 505

Answers (3)

gilly3
gilly3

Reputation: 91487

You are closing your call to .load() too early. You have:

$("#gallery").load('http://...'), function() {

That just calls load and then declares a function. But, that function is not bound to the success handler and it will never be executed. You need the ) to be on the other side of the function declaration so that the function is included as a parameter to your call to load:

$("#gallery").load('http://...', function() {
    ...
});

Fix that and your code works: http://jsfiddle.net/gilly3/WdqDY/

Upvotes: 4

SeanCannon
SeanCannon

Reputation: 77956

Try a future-proof event observer like live or delegate:

$('li').live('click', function(){})

or, this method is preferred if you know the parent:

$('#gallery').delegate('li','click',function(){})

The reason for needing this is your click events are being bound to elements that are on the page at the time of the binding. Any li's added later will not see that binding which is how live or delegate works. They bind to the parent and traverse the child nodes every (click in this case) event to see if the event applies to an existing child.

Upvotes: 2

Matt Ball
Matt Ball

Reputation: 359776

Use .live('click', ...) or .delegate() instead of .click(...).

Upvotes: 1

Related Questions