YVLL YVLL - 1 year ago 74
Javascript Question

Adding Class to Element when it's at the Top of the Screen

I am trying to add class to elements that hit the top of the screen that have been appended either by clicking a button inside a parent DIV or by entering text within the input form.

It works, but not for the appended elements. And when it does work for the appended elements, it's like the offset of those elements get off each time they get appended and then it applies the class to every appended element after that. It's annoying and I've been stuck on this for at least a week now.

The code I am using to add class when the element hit the top of the screen is this:

window.poo = function poo() {
$("#message").each(function() {

var win = $(".chat-log"),
nav = $(this),

pos = nav.offset().top,
sticky = function() {

win.scrollTop() > pos ?
nav.addClass('inactive') :




The elements parent is #message and the #message's parent is .chat-log. I have changed #message to .message but it still gave me the same result.

And when the user clicks the buttons within the parents, the offset gets worse each time and the class is applied to all elements before they even hit the top of the screen.

A working example of this is here.

I tried doing this here but only the element already showing does the trick.

Answer Source
$(".chat-log").on("scroll", function() {  
    console.log("I'm scrolling!");

    var win = $(this);  // .chat-log

        var nav = $(this);  // each .message found

        //console.log("win: "+win.scrollTop());
        console.log("nav: "+nav.offset().top);

        nav.offset().top < 0 ? nav.addClass('inactive') : nav.removeClass('inactive')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download