Detect If An Element Appears On The Screen - scroll_element_detector.js

File Size: 2.44 KB
Views Total: 510
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Detect If An Element Appears On The Screen - scroll_element_detector.js

If you are looking to improve the user experience of your web applications, and in particular if you want to trigger some action when an element is about to be scrolled into view, then this post is for you.

scroll_element_detector.js is a super tiny jQuery plugin that detects if an element is scrolled into view and triggers a certain action (like running a CSS3 animation or showing a modal window) when the matched element is visible.

How to use it:

1. Download the package and load the main script scroll_element_detector.js after jQuery.

<script src="/path/to/cdn/jquery.slim.min.js"></script>
<script src="/path/to/scroll_element_detector.js"></script>

2. Add the data-scroll to the target element on which you want to detect the visibility.

<section data-scroll>
  Page Section 1
</section>
<section data-scroll>
  Page Section 2
</section>
<section data-scroll>
  Page Section 3
</section>
...

3. Change the styles of the element when it is scrolled into view.

[data-in-view] {
  background-color: #222;
}

4. Trigger a function when it is scrolled into view.

<section data-scroll="myFunction(para)">
  Page Section 1
</section>
function myFunction(para) {
  // do something
}

5. Define the top offset of the element.

<section data-scroll="myFunction('para')" data-scroll-offset="500">
  Page Section 1
</section>

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