Chris Cook Chris Cook - 6 months ago 26
CSS Question

How to call a function for each element with a particular class, every time the window scrolls (jquery))

I am trying to make a scroll-triggered function which slides elements in from one side based on the scroll position. I would like it to run on all elements with 'my-class', but currently my code seems to think 'this' is the window, not each 'my-class' element. Is there something wrong with the way I am calling the function? How can I get each element to run the function?

Here is the basic html structure:

<div class="wrapper">
<div class="my-class"></div>
<div class="not-my-class"></div>
<div class="my-class"></div>
<div class="not-my-class"></div>
<div class="my-class"></div>
</div>


some CSS:

.wrapper {
width: 100%;
height: 100%;
}
.my-class, .not-my-class {
width: 100%;
height: 350px;
margin-top: 10px;
background-color: #888888;
}


And the jquery:

function fadeIn($element) {
$scrollTop = $(window).scrollTop();
$windowHeight = $(window).height();
$pageHeight = $('body').height();
$elementHeight = $($element).height();
$baseOffset = $($element).offset().top;
$length = 100;
$finalOffset = $baseOffset + ( $elementHeight / 2 );
$current = ( $scrollTop - ( $finalOffset - ($windowHeight / 2 ) - ( $length / 2 ) ) ) / $length;
if ($current > 1) {
$current = 1;
}
else {
if ($current < 0) {
$current = 0;
}
else {}
}
$opacity = $current;
$slide = ( $current * 100 ) - 100;
$(this).css({"opacity": $opacity, "left": $slide, "position": "relative"});
}
$(window).on("load resize scroll",function(){
$('.my-class').each(fadeIn(this));
});

Answer

You need to pass in a function like so:

$('.my-class').each(function(){ 
  fadeIn(this) 
});

So that this is referring to the .my-class element instead of the window