Modern websites often incorporate animations into their designs. I had the idea to animate elements as we scroll down the page, using a combination of JQuery, HTML, and CSS.
<div class="noanimate imgleft">
</div>
<div class="noanimate imgright">
</div>
The classes "imgleft" and "imgright" position elements to the left and right, respectively. The "noanimate" class initially hides elements with zero opacity and sets up transition properties for animation.
After creating the HTML structure, we apply the following CSS:
.noanimate{
display:inline-block;
opacity:0;
transition:0.55s ease-in;
}
.imgleft.noanimate{
left:-20%;
}
.imgright.noanimate{
right:-20%;
}
This CSS code moves the elements 20% off-screen to create a floating effect. Now, let's look at the essential part - JQuery. We need to ensure that our animation is triggered only when the element is visible in the viewport.
A:- First, identify the elements and attach a window scrolling function.
var $section=$(".noanimate"),
$window=$(window);
$window.on('scroll',function(){
$section.each(function(i,elem){
if($(elem).hasClass('view')){
return ;
}
else {
checkView(elem);
}
});
});
B:- Check if the element is within the viewport by comparing its position relative to the window scroll.
function checkView(elem){
var viewTop=$(window).scrollTop(),
viewBottom=viewTop+$(window).height(),
sectTop=$(elem).offset().top,
sectBottom=sectTop+$(elem).height();
if(sectTop>=viewTop && sectBottom<=viewBottom){
switchClass(elem);
}
function switchClass(elem){
$(elem).removeClass('.noanimate').addClass('view');
}
}
If needed, you can also use JavaScript to handle older browser versions where CSS3 transitions may not work smoothly.
Check out this JsFiddle link for a demo.
Happy Coding :)