How to add a class to body tag based on the section which is in viewport

Viewed 328

Hey I am new in jquery and i am stuck, I have html like this

<section id="help">Help</section>
<section id="touch">Touch</section>
<section id="payment">Payment</section>
<section id="toys">Toys</section>

So now if touch section is in viewport then add class to body (body class name is "touch-active")

and i am trying this code but it is not working for me:

jQuery(document).ready(function(){
   if (jQuery('section').is(':visible')){
         jQuery('body').addClass(.attr('id + active'));;
    }
 });

Thanks in advance :)

1 Answers

To achieve this you can use an IntersectionObserver to detect when an element comes in to view. From there you can remove all classes from the body and replace it with a new class based on the visible section. Try this:

var targets = document.querySelectorAll('section')
var obsOptions = {
  root: null, // measure against the viewport
  threshold: .5 // how much of the element should be visible before handler is triggered
}

let handler = (entries, opts) => {
  entries.forEach(entry => {
    if (entry.intersectionRatio > opts.thresholds[0]) {
      document.body.classList.remove(...document.body.classList);
      document.body.classList.add(entry.target.id + '-active');
    }
  })
}

targets.forEach(el => {
  var observer = new IntersectionObserver(handler, obsOptions);
  observer.observe(el);
})
section {
  height: 250px;
}

body.help-active { background-color: #FFFFFF; }
body.touch-active { background-color: #DDDDDD; }
body.payment-active { background-color: #BBBBBB; }
body.toys-active { background-color: #999999; }
<section id="help">Help</section>
<section id="touch">Touch</section>
<section id="payment">Payment</section>
<section id="toys">Toys</section>

Related