Add Classe when the item visible

Add class on scroll to viewport jquery code

The idea of this code, sometimes we need to add a class when the user scrolls and comes to a target element. Maybe we need to animate it or any other purpose.

Use the jQuery code below and add your own class.

Custom.js
function isScrolledIntoView(elem) {
  var docViewTop = $(window).scrollTop();
  var docViewBottom = docViewTop + $(window).height();

  var elemTop = $(elem).offset().top;
  var elemBottom = elemTop + $(elem).height();

  return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

$(window).scroll(function () {
  $('.taget_class').each(function () {
      if (isScrolledIntoView(this) === true) {
          $(this).addClass('active');
      }else{
        $(this).removeClass('active');
      }
  });
});

Copy the code and change target_class to your target element class or you can use id with the # sign. In the final result, you will see when you scroll to the element an active class added.

Bookmark this site for more useful and amazing code snippet in future.

Previous Code

Remove Website field from WordPress comment & Change cookies remember text

Remove Website field from WordPress comment & Chan ...

Next Code

Elementor text editor Typography Issue [solution]

Elementor text editor Typography Issue [solution] ...

0 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

two × 4 =

Cookie Popup with jQuery

Browser cookies popup accept, store cookies in bro ...

Sticky Menu Show when scrolling up

Header bar only show when scrolling up with simple ...

Simple jQuery Accordion Collapse

Custom coded Simple jQuery Accordion with toggle a ...

JQuery Auto Hight

jQuery height change after a specific time interva ...

Custom tab

...

ACF

JavaScript

jQuery

Others

PHP

WooCommerce

WordPress

skype

Need Coding Help?

Connect Skype
top