How to bind to 'inview' event on multiple elements

2.9k Views Asked by At

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?

2

There are 2 best solutions below

4
On BEST ANSWER

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/

3
On

The best solution is to use a single class on each of these elements since they have something so in common. You might just add title as a class type and apply it to that class.

<div class="title movie-title"></div>

I know you mentioned this in your question, but I can't see why this wouldn't work.