I am trying to use waypoints.js to have elements fadein when scrolling to hit the elements.
I have
$(document).ready(function(){
$('.card').waypoint(function(down) {
console.log('hit element');
$(this).addClass('card-fadeIn');
}, { offset: '100%' });
});
What this does is adds the class 'card-fadeIn' which is opacity 1 and an ease in animation.
When I change it to
$('.card').addClass('card-fadeIn');
It works fine, but adds opacity 1 to every card class and ruins the fadein effect. I was trying to use $(this) instead but it wont fadein, nor will it give an error in the console. Any ideas why?
I am trying to use waypoints.js to have elements fadein when scrolling to hit the elements.
I have
$(document).ready(function(){
$('.card').waypoint(function(down) {
console.log('hit element');
$(this).addClass('card-fadeIn');
}, { offset: '100%' });
});
What this does is adds the class 'card-fadeIn' which is opacity 1 and an ease in animation.
When I change it to
$('.card').addClass('card-fadeIn');
It works fine, but adds opacity 1 to every card class and ruins the fadein effect. I was trying to use $(this) instead but it wont fadein, nor will it give an error in the console. Any ideas why?
Share Improve this question asked Aug 12, 2015 at 14:35 ServerSideSkittlesServerSideSkittles 2,97312 gold badges39 silver badges62 bronze badges 5- Can you log what this is inside that function? – Jack Guy Commented Aug 12, 2015 at 14:37
-
this
could be very different to what you think it is. – Johan Commented Aug 12, 2015 at 14:37 -
this
is probably not the jQuery object scope anymore. Savethis
in some variable before. – Lars Graubner Commented Aug 12, 2015 at 14:38 -
I think, because in this case
this
is thewaypoint
. Console logthis
to inspect what is that. Try to pass the element to that function. – vaso123 Commented Aug 12, 2015 at 14:40 - Yep console log gives me element and a few other options – ServerSideSkittles Commented Aug 12, 2015 at 14:47
2 Answers
Reset to default 11You have to use
$(this.element)
in a Waypoint handler. So,
$(this.element).addClass('card-fadeIn');
should do what you want.
$(this)
works inside jQuery callbacks because jQuery is designed for things to work that way. There's nothing magic about it, however, so if this
doesn't refer to a DOM element, you'll get a jQuery object that won't do anything (and which won't report any errors, because, again, that's just how jQuery works). The Waypoint library binds this
to its own context object, and that exposes a reference to the DOM element involved in the callback as the "element" property.
Have you tried this.element?
$(document).ready(function(){
$('.card').waypoint(function(down) {
console.log('hit element');
$(this.element).addClass('card-fadeIn');
}, { offset: '100%' });
});