Reputation: 155
How come variables such as img : $('img')
in my function are losing their value after an ajax call. Here is an example function.
imageFades: {
img : $('img'),
init: function() {
this.img.fadeIn(200)
console.log('fire')
}
}
After the ajax call the console.log fires, but the fadeIn does not. I've tested directly adding $('img').fadeIn(200)
to the init function and that works fine. What is exactly going on?
Upvotes: 0
Views: 89
Reputation: 14053
It's hard to say for sure without seeing your entire code, but most likely you have confused the use of this
. In a jQuery AJAX response function, this
is not set to a created object. To quote the jQuery API:
The
this
reference within all callbacks is the object in the context option passed to$.ajax
in the settings;
Upvotes: 0
Reputation: 707806
If you replaced your images in the ajax call (which it sounds like) or any time after the imageFades
object was created, then you will have to rerun the selector so that it can see the newly added images.
imageFades: {
init: function() {
$('img').fadeIn(200);
console.log('fire')
}
}
jQuery objects are not "live". They don't keep up with changes in the DOM. They represent a snapshot of what was in the DOM at the time you created the jQuery object and that point in time that it ran the selector query.
Upvotes: 4