sfuptown
sfuptown

Reputation: 287

Jquery - How to initialize elements added to DOM via Ajax call

This worked when content was NOT added via ajax

$('#element a img').css({ 'opacity': '0.5' });

However it doesn't work when the elements are added via an ajax call. I am familiar with live and bind, but those are for events.

After I add the elements via ajax, I need to do some initialization like adding a span to first one and also setting the opacity on the newly added items, etc.

How can I initialize elements added via ajax?

Upvotes: 0

Views: 2922

Answers (3)

WhiskeyTangoFoxtrot
WhiskeyTangoFoxtrot

Reputation: 644

The initial function call you specify works for "not loaded by AJAX" DOM elements because when you call it, it only performs the specified on DOM elements matching the selector at the time the function is called. You're basically saying, 'do this on all elements and stop.' It does not watch the DOM for new elements that match the selector.

As part of the $.ajax()/.get()/.post callback function you could perhaps make the call to the $().css(); function

And although deprecated, perhaps $.live(); will suit your needs for now. $.live(); is currently being superceded by $.on(); but $.delegate(); can also suit your needs.

Although perhaps not most the syntactically correct (it is 3 AM!) I made a quick JSFiddle to use $.delegate(); at http://jsfiddle.net/ZpN2y/

Just click the input button and click the created divs. You can see I only call delegate once, and outside the div appender. This could very possibly adapted to your use. Unfortunately my experience with .delegate and .on are absolutely nil.

Upvotes: 1

adeneo
adeneo

Reputation: 318312

Try setting the css rules in the Ajax complete handler, when the element actually exists on the page:

$.ajax({
    url: 'ajax/test.html',
    success: function(data) {  },
    complete: function() { 
        $('#element a img').css('opacity', '0.5'); 
    }
});

Upvotes: 5

hendrikswan
hendrikswan

Reputation: 2341

Even if you added the elements through an ajax call, a normal jQuery selection should still work.

Try to use the developer tools in Chrome, IE or Firefox to ensure that the elements you inserted with the ajax call does indeed conform to the structure you expect.

Upvotes: 0

Related Questions