December 28, 2024
1 min read
Essential Code Snippet For Web Developers

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.

Leave a Reply

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

Add an additional custom checkbox in the WooCommerce checkout

Add an additional custom checkbox after the terms and conditions in WooCommerce checkout we can use WooCommerce

How to Add Page Template from Your Plugin

Add custom page template from your plugin with simple code snippet.

ACF

Filter custom post type by Custom Field (ACF) in the admin area

Show filter on custom post type admin area with custom field value

Jquery Replace specific text in all element

Scenario Imagine you have a set of elements with the class specific_class, and they all contain the phrase “old text.” You want to replace this phrase with “New text” programmatically. The Solution Here’s a simple jQuery script to achieve this: How It Works Things to Keep in Mind Extending the Script jQuery provides a quick […]

Web Development Project in mind?

if you looking for a web developer for paid contribution to your project I am available for work.

Mukto
Mukto

Click the button below to chat with me.