1

I have an <img> tag which already has the icon class.

I need to add two extra classes to that element for [animate.css] (http://daneden.github.io/animate.css/) animations.

Those extra classes, flip and animated, need to be added once the user scrolls to the image.

I tried a lot of different ways but none of them worked. Here's the html:

<div class="col-md-12 ">
    <div class="box">
        <img src="img/world.png" class="icon"/>
        <h1>WEB<br/>DESIGN</h1>
    </div>
</div>

The users should scroll down around 1328px so that the animations starts.

Bottom line: How do I add flip and animated classes to <img> when the user scrolls to it?

Danny Varod
  • 15,783
  • 5
  • 58
  • 98

3 Answers3

2

You could do this: http://jsfiddle.net/AndyMardell/rqgh699w/

I used the following "isScrolledIntoView" function from this post: Check if element is visible after scrolling

function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop(),
        docViewBottom = docViewTop + $(window).height(),
        elemTop = $(elem).offset().top,
        elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

$(window).scroll(function(){
    if (isScrolledIntoView('.box')) {
        $('img').addClass('animated flip').css('background', 'red');
    }
});

It waits for your parent .box element to be visible in the window, then triggers

Community
  • 1
  • 1
Andy Mardell
  • 806
  • 6
  • 13
0

Try something like

window.onscroll = function() { 
  var scrollTop = window.pageYOffset;
  if(scrollTop > 1328) {
    //do what you want.
    alert(scrollTop);
  }
}

Is that what you needed?

Kevin
  • 17
  • 5
-1

You can use the onscroll event listener and the scrollTop property to wait until it's time to add those classes, something like:

window.onscroll = function() {
    if (document.body.scrollTop > 1328) {
        // add your classes
    }
}

You can use .className (stackoverflow, MDN) to actually add the classes:

document.querySelectorAll("img.icon")[0].className += " animated flip";
//                                                     ^ note this space

.querySelectorAll could just as easily be replaced with .getElementsByClassName("icon").

If you need a one-time use animation, the above examples will be fine, it looks like this:

window.onscroll = function(){
    if (document.body.scrollTop > 1328){
        document.querySelectorAll("img.icon")[0].className += " flip animated";
    }
}

here's a JSFiddle.

If you need the animation to trigger every time, check out this well-commented JSFiddle

Community
  • 1
  • 1
theonlygusti
  • 7,942
  • 8
  • 40
  • 80