December 28, 2024
2 min read

Sometimes we need to dynamically manage classes based on whether certain elements are visible in the user’s viewport. In this blog post, we’ll explore how to add and remove classes using JavaScript and jQuery, enhancing your website’s interactivity and responsiveness.

Detecting Element Visibility

Before we dive into the implementation, let’s understand the concept of viewport visibility. The viewport is the visible area of a web page displayed in the browser window. We want to determine whether a specific HTML element is currently within this viewport.

The isElementInViewport Function

function isElementInViewport(el) {
  var rect = el.getBoundingClientRect();
  return (
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
    rect.right <= (window.innerWidth || document.documentElement.clientWidth)
  );
}

JavaScript

This function takes an HTML element as its parameter and returns true if the element is in the viewport and false otherwise. It calculates the element’s bounding rectangle and checks whether all four sides are within the viewport boundaries.

Managing Element Visibility

Now, let’s create a function that handles the addition and removal of classes based on the visibility status of a given element.

The handleElementVisibility Function

function handleElementVisibility() {
  var targetElement = $(".your-target-class");

  if (!isElementInViewport(targetElement[0])) {
    targetElement.addClass("out-of-view");
  } else {
    targetElement.removeClass("out-of-view");
  }
}

JavaScript

This function uses jQuery to select the target element with the class “your-target-class.” If the element is not in the viewport, it adds the class “out-of-view”; otherwise, it removes this class.

Initialization and Event Handling

To ensure the initial state is correct and to continuously check for changes, we’ll call the handleElementVisibility function on page load and attach it to the window scroll event.

$(document).ready(function() {
  handleElementVisibility();

  $(window).on("scroll", function() {
    handleElementVisibility();
  });
});

JavaScript

This ensures that the visibility check is performed when the page loads and whenever the user scrolls.

Full code as an example

Script.js
// Function to check if an element is in the viewport
    function isElementInViewport(el) {
      var rect = el.getBoundingClientRect();
      return (
          rect.top >= 0 &&
          rect.left >= 0 &&
          rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
          rect.right <= (window.innerWidth || document.documentElement.clientWidth)
      );
  }

  // Function to handle the class addition
  function handleElementVisibility() {
      var targetElement = $(".cart_total_area");
      if (!isElementInViewport(targetElement[0])) {
          // If the element is out of view, add the custom class
          targetElement.addClass("out-of-view");
      } else {
          // If the element is in view, remove the custom class
          targetElement.removeClass("out-of-view");
      }
  }

  // Initial check on page load
  handleElementVisibility();

  // Check again when the window is scrolled
  $(window).on("scroll", function() {
      handleElementVisibility();
  });

JavaScript

Conclusion

By incorporating this dynamic class management technique into your web development projects, you can create a more interactive and visually appealing user interface. Whether you’re highlighting elements as they come into view or triggering animations, the ability to add and remove classes based on visibility in the viewport opens up a world of possibilities for enhancing user experience.

Experiment with different classes and styles, and tailor this approach to suit your specific design and functionality needs. As you integrate this technique into your projects, you’ll find that it adds a layer of sophistication to your websites, making them not only functional but also aesthetically pleasing.

Leave a Reply

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

Making Specific Products Unpurchasable or purchasable for a specific date in WooCommerce

How to make specific products not purchasable in WooCommerce using code.

Simple jQuery Accordion Collapse

Custom coded Simple jQuery Accordion with toggle arrow. No need extra plugin or fremwork like bootstrap

Get WooCommerce product info

Show product info in the place as you wish to. It help you to make your custom woocommerce product page layout.

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

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.