Skip to content Skip to sidebar Skip to footer

Dynamically Add Css Class To Fixed Div When It Is Scrolled To Another Html Element

I read several similar questions here on StackOverflow, alas none of the solutions quite worked for me. I want to dynamically add a css class to html element when it is scrolled d

Solution 1:

Hope this helps

$(function () {
    var menu = $('#fixedbtn');

    functionisInViewport($this) {
        var elementTop = $this.offset().top;
        var elementBottom = elementTop + $this.outerHeight();
        var viewportTop = $(window).scrollTop();
        var viewportBottom = viewportTop + $(window).height();
        if (elementTop < viewportBottom == true) {
            menu.addClass('fixedPosition');
        } else {
            menu.removeClass('fixedPosition');
        }
    }

    $(window).scroll(function () {
        isInViewport($('#footer-1'))
    });
});
.conatiner {
  height: 2000px;
}

#footer-1 {
  background-color: red;
  position: relative;
}

#fixedbtn {
  background-color: blue;
  width: 55px;
  height: 20px;
  position: fixed;
  left: 0;
  bottom: 0;
}

#fixedbtn.fixedPosition {
  background-color: white;
  position: absolute;
  left: 0;
  top: 0;
}

.stuck {
  height: 800px;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script><divclass="conatiner"><divclass="stuck"><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet
            dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper
            suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in
            vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et
            accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait
            nulla facilisi.</p></div><divid="footer-1"><divid="fixedbtn">
            fixedbtn
        </div>
        #footer-1
    </div></div>

Post a Comment for "Dynamically Add Css Class To Fixed Div When It Is Scrolled To Another Html Element"