0

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));
});
Chris Cook
  • 404
  • 2
  • 15
  • 1
    Maybe a callback on each? : $(window).on("load resize scroll",function(){ $('.my-class').each(function(){FadeIn(this) } ); }); – user3791775 May 25 '16 at 01:28
  • 1
    Great examples in the [docs](http://api.jquery.com/each/). The basic problem is [`this`](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) in your code is from the outer anonymous function. – Jasen May 25 '16 at 01:34
  • Thanks guys, that has fixed it. @user3791775 if you want to post that as an answer I'll accept it. working a treat now. Edit: There has just been two more correct answers. Thanks all! – Chris Cook May 25 '16 at 01:46

2 Answers2

1

At first glance you should change the each call to

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

so it runs at the right moment and gains the correct scope.

1

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

AJ Funk
  • 2,374
  • 14
  • 18
  • This answer worked. Here is the correct code for reference. `$(window).on("load resize scroll",function(){ $('.my-class').each(function(){ fadeIn(this); }); });` – Chris Cook May 25 '16 at 01:47