Ricardo Patrick
Ricardo Patrick

Reputation: 81

jquery and event scroll

i have 1 class html with various elements i want add a class new class in first element that scroll top reach the top ofos this elements, then when the scroll reach the second add in second too and so on. i tried this

var element = $(".element"); 
        $(window).scroll(function () {
            var scroll = $(window).scrollTop();
            for(var i = 0; i < element.length;i++){
                if(scroll > element.eq(i)){
                    element.eq(i).addClass("newClass");
                }
   }
})

html piece

<div>
    <div class="element">
        <img src="img/image1" />
    </div>
    <div class="element">
        <img src="img/image2" />
    </div>
    <div class="element">
        <img src="img/image3" />
    </div>
</div>

but this line element.eq(i).addClass("newClass") dont work :) how i should to do

Upvotes: 0

Views: 40

Answers (1)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

try to use

if(scroll > element.eq(i).offset().top - ($(window).height() / 2) ){
    element.eq(i).addClass("newClass");
 }

DEMO

Upvotes: 1

Related Questions