Adding And Removing Class Based On Element Visibility In The Viewport | Code For Developers

Adding and Removing Class Based on Element Visibility in the Viewport

Add class on element if it come in view and remove not in view

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)
  );
}

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");
  }
}

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();
  });
});

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();
  });

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.

Previous Code

Enabling Guest Checkout in WooCommerce: Bypassing Email Verification for Order Payment

Enable guest payment, bypass email verification. E ...

Next Code

Add custom Elementor widgets in the Hello child theme

learn how to add custom Elementor widgets to the H ...

Leave a Reply

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

If you find it useful

Buy me a coffee

ACF

Elementor

JavaScript

jQuery

Others

PHP

WooCommerce

WordPress

WP Plugin Dev

Jquery Replace specific text in all element

...

Simple jQuery Accordion Collapse

Custom coded Simple jQuery Accordion with toggle a ...

Jquery Custom Tab

...

Cookie Popup with jQuery

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

Sequential Fading jQuery Text Animation

This code animates text using jQuery, creating a s ...

top