Fusiqos Fusiqos - 7 months ago 28
Javascript Question

How to check if div reaches top of page for each div?

This is my current solution to check if a specific div reaches the top of the page, which i got from here http://stackoverflow.com/a/5279537/4671165

document.addEventListener("scroll", Scroll, false);

function Scroll() {
var top = $('.element').offset().top - $(document).scrollTop();

if (top < 150){
var textvariable = $('.text').text();
}
}


But i want this to do something each time a different div reaches the top of the page, therefore i currently have

var top1 = $('.element1').offset().top - $(document).scrollTop();
var top2 = $('.element2').offset().top - $(document).scrollTop();
var top3 = $('.element3').offset().top - $(document).scrollTop();

if (top1 < 150 && top2 > 150){
var textvariable = $('.text1').text();
}

if (top1 < 150 && top2 < 150 && top3 > 250){
var textvariable = $(.text2').text();
}

if (top2 < 150 && top3 < 250){
var textvariable = $(.text3').text();
}


However, this doesn't seem the most effective way but i can't figure out what is. Especially since i have more elements then just 3 in the project. So i am looking for a more effective way.

Answer

I found a jquery solution

function ScrollStart() {

var scrolled = $(this).scrollTop();


/*filter current element at the top with a certain class & give it active class*/

$('.step').removeClass('activetext').filter(function() {
     return scrolled <= $(this).offset().top + $(this).height() - 50 && scrolled >= $(this).offset().top - 50;
}).addClass('activetext');

/* make exclusion for first element */

var boven = $('.first').offset().top - $(document).scrollTop();

if (boven > 0){     
   $('.first').addClass('activetext');
} 

/*make exclusion for last element*/

var bottom = $('.last').offset().top - ($('.last').height()/5) - $(document).scrollTop();

if (bottom < 150){
    $('.step').removeClass('activetext')
   $('.last').addClass('activetext');
} 
else{ 
    $('.last').removeClass('activetext')
}

    /* give variable 'text' the text of the active class & append it */

var text = $('.activetext .headertekst').text();
$('.dropbtn').empty();
$('.dropbtn').append(text);
    $('.dropbtn').append('<img src="images/downarrow.svg" galleryimg="no"></img>');

}