I'm trying to make an animation that I've created start when in the screen's viewport.
// Returns true if the specified element has been scrolled into the viewport.
function isElementInViewport(elem) {
var $elem = $(elem);
// Get the scroll position of the page.
var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
var viewportTop = $(scrollElem).scrollTop();
var viewportBottom = viewportTop + $(window).height();
// Get the position of the element on the page.
var elemTop = Math.round($elem.offset().top);
var elemBottom = elemTop + $elem.height();
return ((elemTop < viewportBottom) && (elemBottom > viewportTop));
}
// Check if it's time to start the animation.
function checkAnimation() {
var $elem = $('.image-container')
if (isElementInViewport($elem)) {
// Start the animation
$elem.addClass('start');
} else {
$elem.removeClass('start');
}
}
// Capture scroll events
$(window).scroll(function() {
checkAnimation();
});
/* slide reveal aniamtion */
@keyframes left {
0% {
transform: translatex(-100%);
}
100% {
transform: translatex(0%);
}
}
/* animation */
.animated-container {
width: 600px;
height: 600px;
background: #f5f5f5;
overflow: hidden;
}
.image-container {
width: 100%;
height: 100%;
background: pink;
transform: translatex(-100%);
}
.start {
animation: left 2s ease-out forwards;
}
.float-right {
float: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="animated-container">
<div class="image-container">
</div>
</div>
For some reason, the class does not seem to be applying to the container box when in view and is returning an error. Can anyone help me out with what's going wrong on this and why it what could be stopping the javascript from adding the class.
Line 68 (the first line in your checkAnimation
function) reads $(".image-container');
. Note how you've used double quotes to start the string, but a single quote to end it.
Just change that to $('.image-container')
and you should be fine :)
$
is not defined. You're using $(element)
but you haven't defined what $
does or means. How about linking jQuery to your project? Or at least define $
to be shorthand for the querySelector function?
.start
class - the start class alone though is not enough to start the animation. Your css file adds the animation on elements with .left.start
, so either change that to trigger on only the .start
class or add the .left
class just like you add the .start
class.