The following example makes a CSS animation run only when it is in the user’s field of view, which is achieved, for example, by scrolling. Thereby an image becomes visible, which results in a drawn line.
The drawn line already exists as an image. By CSS this is completely hidden at the beginning and then slowly visible, so that the effect of a line drawn from top to bottom is created.
<div class="contain-element"> <img class="prints" src="/line.png" alt="Linie"> <span class="cover"></span> </div>
.contain-element {
position: relative;
text-align: center;
}
.cover {
position: absolute;
left: 0;
background: #fff;
height: 1000px;
width: 1420px;
}
@keyframes walk {
to {
transform: translateY(675px);
}
}
<script>
jQuery ( function($) {
$(document).ready(function(){
$(window).scroll(function(){
if ($('.contain-element').isOnScreen()) {
$(".cover").css("animation","walk 4s steps(28, end) forwards");
} else {
// The element is NOT visible, do something else
}
});
});
$.fn.isOnScreen = function(){
var win = $(window);
var viewport = {
top : win.scrollTop(),
left : win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};
} );
</script>