Skip to content

Instantly share code, notes, and snippets.

@prashantsani
Last active November 6, 2019 07:41
Show Gist options
  • Save prashantsani/15cefdce2327cb4a02f6817a6637233e to your computer and use it in GitHub Desktop.
Save prashantsani/15cefdce2327cb4a02f6817a6637233e to your computer and use it in GitHub Desktop.
JavaScript IntersectionObserver Utility Function - Trigger When Element in View
// View Comment section for explanation
function _$(elem){ return d.querySelectorAll(elem) }
function observer(trigger, func_vis, func_hidden, threshold){
var t = threshold ? threshold : 1,
observable_var;
observable_var = new IntersectionObserver(
entries => {
if (entries[0].isIntersecting){
func_vis()
}
else{
func_hidden()
}
},
{
threshold: t
}
).observe(_$(trigger)[0]);
return observable_var;
}
@prashantsani
Copy link
Author

Explanation:

  • If 80% percent (or more than 80%) of the .hero element is visible, then it will trigger alert('visible')
  • Else, it will trigger alert('hidden')
// Arrow Function Way -- Recommended/Preferred if there is no issue with `this` binding 
var test = observer('.hero', () => alert('visible'), ()=> alert('hidden'), 0.8);

// Traditional way (ES5)
var test = observer('.hero', function() { alert('visible') }, function() {alert('hidden')}, 0.8);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment