V
V
Vladimir Novitsky2015-10-09 18:03:31
JavaScript
Vladimir Novitsky, 2015-10-09 18:03:31

How to change the class of the body when scrolling to a specific element?

Hello.
It is necessary that when scrolling the page to a block with a specific id, a class is added to the body. And when scrolling above, the class was removed.
How can this be done with jQuery?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaly Inchin ☢, 2015-10-09
@Novitsky

document.onscroll = function(){
  var what = document.querySelector("#id").getBoundingClientRect().top;
  document.body.classList.toggle(
    "class", what <= window.innerHeight
   );
}

jsfiddle.net/eoeyuo30/1
Or on jq :
$(document).scroll(function(){
  var what = $("#id").offset().top, 
        pos = $(window).height() + $(window).scrollTop()
  $("body").toggleClass("class", what <= pos);
});

jsfiddle.net/eoeyuo30/2

A
Andrew, 2015-10-09
@Menlod

More or less like this

$(window).on('scroll', function(){
    if($(window).scrollTop() >= $('.element').offset().top){
      $('body').addClass('new-class');
    }
  });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question