Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
76
rated 0 times [  79] [ 3]  / answers: 1 / hits: 26952  / 6 Years ago, fri, september 7, 2018, 12:00:00

I am writing a script that gives different elements some animations when they appear in the screen.



Step one would be to detect when they come in the screen. But that doesn't seem to work.



What I tried:



-The .visible() selector, I quickly found out this does something else in jQuery.



-Different plugins, but I found that they do way more then I need, therefore I decided to write/ find something myself.



-My current script (I found it somewhere in a forum and decided to edit it to my needs) But It works a little strange.



$.fn.isInViewport = function () {
let elementTop = $(this).offset().top;
let elementBottom = elementTop + $(this).outerHeight();

let viewportTop = $(window).scrollTop();
let viewportBottom = viewportTop + $(window).height();

return elementBottom > viewportTop && elementTop < viewportBottom;
};

$(window).scroll(function () {
if ($('.blogcard ').isInViewport()) {
$(this).addClass(test);
console.log('success.')
} else {
console.log('No success.')
}
});


Unfortunately this doesn't seem to add a class to my <div class='blogcard'>.


More From » jquery

 Answers
21

Your use of this targets window not .blogcard element:



$(window).scroll(function () {
if ($('.blogcard ').isInViewport()) {
// Use .blogcard instead of this
$('.blogcard').addClass('test');
console.log('success.')
} else {
// Remove class
$('.blogcard').removeClass('test');
console.log('No success.')
}
});

[#53545] Monday, September 3, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maureen

Total Points: 151
Total Questions: 110
Total Answers: 110

Location: Mali
Member since Fri, Dec 3, 2021
2 Years ago
;