Codefoe
Codefoe

Reputation: 31

Can't do anything with .load()-ed content in jQuery?

I'm facing an interesting problem where everything works flawlessly. I console.log every step and it plays out just the way it should. But! I have a #div into what I .load(a-file.php). Now that "a-file.php" includes HTML mark-up as well, more specifically certain links that I'd like to make "active" onload.

Scenario; page load happens, Javascript loads and loads a file into the div. That div now has tabs and I'd like the first tab to be in an "active" state which requires me to addClass('active');. But the following seems to have no effect

$('#content').load('file.php'); // works.
$('#content a[rel="weird-page"]').addClass('active'); // does not work.

Any kind of help, even remotely nailing it, is appreciated.

Upvotes: 0

Views: 51

Answers (2)

Curtis
Curtis

Reputation: 103348

jQuery load() works asynchronously and therefore your addClass() method is being called before load() has completed.

Using the load() callback function it will ensure your content has loaded:

$('#content').load('file.php', function() {
   $(this).find('a[rel="weird-page"]').addClass('active');
});

shameless-plug-warning: I wrote a blog post about jQuery callback functions which you might find useful.

Upvotes: 1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

change to:

$('#content').load('file.php', function() {
   $('#content a[rel="weird-page"]').addClass('active');
}); 

Upvotes: 1

Related Questions