Search code examples
javascriptjqueryvelocity.jsinview

How to bind to 'inview' event on multiple elements


I'm playing around with Velocity.js and jquery.inview, and I want all the titles on my page to slideDownIn when they come into view. This code works fine for the first title:

$('.movies-title').bind('inview', function(event, isInView, visiblePartX, visiblePartY) {
  if (isInView) {
    // element is now visible in the viewport
    if (visiblePartY == 'top') {
      // top part of element is visible
    } else if (visiblePartY == 'bottom') {
      // bottom part of element is visible
    } else {
      // whole part of element is visible
      $(this).velocity("transition.slideDownIn", 500);      
    }
  } else {
    // element has gone out of viewport
    $(this).velocity("reverse");
  }
});

If I copy and paste the above several times and replace .movies-title with the classes of the other titles, it works as I want it to.

However, that seems like a lot of extra code. I tried changing $('.movies-title') to $(.movies-title, .tv-title, .books-title) but then the animation only works for the last element in the list. I also tried adding a new class called .title to all of the titles and changing .movie-title to .title but that didn't work either.

What am I doing wrong? How can I condense the code?


Solution

  • Try using delegate instead of bind for multiples. Also make a unified class for all of them (I just used title)

    so like this -

    $('body').delegate('.title','inview', function(event, isInView, visiblePartX, visiblePartY) {
    

    Edit - sorry linked wrong fiddle initially

    see fiddle http://jsfiddle.net/d1g7sLxq/3/