cigarette_unicorn cigarette_unicorn - 3 months ago 25
CSS Question

JavaScript: addClass when element is in viewport using animate.css

I am using animate.css which is nice and simple as I am a beginner. I can get the animation to work and can delay the animation with

animation-duration: 3s
and
animation-delay: 0s;
But I can't find how to trigger it when it comes into my viewport as I scroll down to it. Here is the code I have tried so far:

HTML



<div class="about-container">
<p>Content here...</p>
</div>


CSS



.about-container{
background-color: #a3c17f;
width: 500px;
height:500px;
margin: 0 auto;
}


JAVASCRIPT



$(function() {
if ($("#about-container").length > 0) {
addClass('animated pulse')
}
});
</script>

Answer

Look at your element. You are using class. So it should be $('.about-container'). However you can change it into ID.

$(function() {
   if($('#about-container').length > 0) { // check if there's an element
      $('#about-container').addClass('animated pulse'); // this is how you add class in jquery
   }
}); 

Plain Javascript

var abtContainer = document.getElementById('about-container');

if(abtContainer.length > 0) {
    abtContainer.classList.add('animated pulse'); 
}

However this method don't work on IE8 and below.

So you need to use this if you are supporting old browsers.

abtContainer.className += ' animated pulse';

http://codepen.io/anon/pen/QERZpz

Comments