Add A CSS Class To Elements When Visible - jQuery inView

File Size: 4.59 KB
Views Total: 2855
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Add A CSS Class To Elements When Visible - jQuery inView

inView is a lightweight (1kb minified) jQuery viewport detection plugin that automatically adds the CSS class is-in-view to desired elements when they're scrolled into view.

Ideal for animating DOM elements using CSS3 animations when they become visible within the document.

How it works:

  • Get the current offset scrolled from the top
  • Get the window's height
  • Loop through each of the elements gathered by the selector above the scroll event
  • Get the distance from the top of the document to the top of the element
  • Get the distance from the top of the document to the bottom of this element
  • Check if the top of the element is in the viewport, Or check if the bottom is in view
  • Run the checkWatchedElements function once to see if the plugin needs to add the class to any currently viewable elements before a scroll event

How to use it:

1. Include the JavaScript file inView.jquery.min.js after loading jQuery library (slim build is recommended).

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" 
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" 
        crossorigin="anonymous">
</script>
<script src="inView.jquery.js"></script>

2. Add the CSS class in-view-watcher to the target element you'd like to track the visibility.

<div class="box in-view-watcher">
  element here
</div>

3. That's it. Animate the element using your own CSS3 animations.

.in-view-watcher.is-in-view {
  /*
    your own animations here
  */
}

Changelog:

2019-02-27

  • Fix splicing in the loop causing other elements to be skipped

This awesome jQuery plugin is developed by nox7. For more Advanced Usages, please check the demo page or visit the official website.