Rahul
Rahul

Reputation: 321

Animation for div when it enters the viewport horizontally

I'm creating an infinite horizontal feed where I want to animate the element when it enters the viewport horizontally. I'm trying waypoint.js for this.

JS FIDDLE

<div id="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>

Adding .show to div which will change opacity of div from 0 to 1.

$(function() {
$(".item").each(function(){
   $(this).waypoint(function() {
     $(this).addClass('show');
     }, {
       offset: '100%',
       horizontal: true
     });  
 });      
});

CSS

.item
{
width:500px;
height:250px;
background:red;
color:#fff;
display:inline-block;
opacity:.2;
}
.item.show
{
opacity:1;
}

But now the elements would not change their opacity from 0 to 1 when they enter the viewport horizontally. Any idea why? Sorry, I'm really new to javascript and waypoint.

Upvotes: 6

Views: 713

Answers (2)

imakewebthings
imakewebthings

Reputation: 3398

this inside the waypoint handler is not the element, it is the Waypoint instance. You want to use $(this.element).addClass('show')

Upvotes: 0

DanCouper
DanCouper

Reputation: 850

The 100% width is incorrect; if you change it to 500px (the specified width of the individual items), it will work. This is non-optimal though (you will need to update both the JS and CSS whenever you change anything): a better approach would probably be to get the width of the items via JS, and use that value as the offset.

Percentage values passed to offset are percentages of the viewport, which I assume is not what you want here, rather the offset should be ~the width of each item. At the minute, any item even partially within the viewport is opaque, so you never see any change.

See http://imakewebthings.com/waypoints/api/offset-option/

Upvotes: 0

Related Questions