0

I'm missing something with this code block, but I do not know what. I want to detect when an element is within a viewport and add a class to that element. My math being: taking the position of the element on the page, minus the window height, which (if down the page) results in the distance between the page fold and the element itself. If that distance is greater than or equal to the amount scrolled, then add class.

var windowHeight = $(window).height();
var yPos = $(window).scrollTop();
var element = $('#element').offset().top;

if(element - windowHeight >= yPos) {
    $('#element').addClass('scrolled');
} else {
    $('#element').removeClass('scrolled');
}
  • *«My math being: taking the position of the element on the page, minus the window height...»* Try the reverse: window height minus the position of the element on the page. Mathematically talking, it has more chances to work. – Louys Patrice Bessette Jun 12 '17 at 04:35

1 Answers1

1

you are missing a closing quote at the third line.

var element = $('#element).offset().top;

It should be:var element = $('#element').offset().top;

I dont know exactly what do you need, you just said there is something missing in your code. So I just give you this one. If it's incorrect, ignore my answer.

Tran Ho
  • 1,442
  • 9
  • 15
  • Thank you kimdung, you are correct and I will edit accordingly, but that does not solve my problem. -- I've edited accordingly and by that regard, I should have quotes encasing all of my other elements as well. – Philip Stier Jun 12 '17 at 04:37