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'>
.