0

I am not so good on javascript, and I am trying to load some images into a div, via an external html page, with some opacity function in jquery. Is there a simple function that will re apply the scripts needed once the ajax call has been made. I have seen jquery live, but before I start tearing my hair out, I wondered if I was on the right tracks. Or is there a really simple method I am missing.

1 Answer 1

4

Yes, live and delegate are your friends.

Specifically, you should try to use delegate, because events bound with live bubble up all the way up the DOM before they're caught.

The syntax for delegate is:

$("#parent_element").delegate(
    "#child_selector_event_occurs_on", 
    "click" // <-- Event to declare a handler for
    function() { ... });

The linked documentation page for delegate has some examples.

Edit:

My answer above assumes that you're losing event handlers that are bound to content that's being replaced or updated with AJAX. If you need to do things like re-initialize widgets or run other custom code, you'd benefit by moving that code into a common function and calling it upon a successful load of new content (and in your document.ready handler).

For example:

function init() {
    /* Write initialization code here */
}

$(document).ready(function() { init(); });

/* Later on, when you reload the content: */
$("#ajaxified").load("foo.html", function() { init(); });

Another alternative is the livequery plugin, which I haven't used but I've heard good things about. Specifically, you'd be looking at the helper function functionality:

$('#selector') 
    .livequery(function(){ 
        /* Write code here to execute when a new element matching the 
           selector is added. */
        init();
    });
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for your reply. Still struggling with this. Would I change the following code. function LoadNewContent(id,file){ $("#"+id+" .customScrollBox .content").load(file,function(){ mCustomScrollbars(); }); }
@simon: You should edit your question if you have a more specific issue. delegate and live will only work on event handlers. If you need to reinitialize a widget or run other code, you'll have to do that every time you load the AJAX content.
Sorry Andrew. What you just said was what I meant. I just was not sure on how to phrase it. How do I re initialize or re run the code. Is there a simple way.
@simon: I expanded my answer with some possible routes you could take.
Thanks for that. I am looking at them now. I was looking at live query a little while ago. Will let you know how I get on.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.