Last active
November 10, 2020 13:28
-
-
Save fravelgue/2cb6b2caeb89ba76c856854f4f060569 to your computer and use it in GitHub Desktop.
Facebook Pixel - Is Element Visible
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://developers.facebook.com/docs/facebook-pixel/advanced/ | |
// This code should be loaded together with Facebook Pixel | |
var executeWhenElementIsVisible = function(dom_element, callback) { | |
if (!(dom_element instanceof HTMLElement)) { | |
console.error('dom_element must be a valid HTMLElement'); | |
} | |
if (typeof callback !== 'function') { | |
console.error( | |
'Second parameter must be a function, got', | |
typeof callback, | |
'instead', | |
); | |
} | |
function isOnViewport(elem) { | |
var rect = elem.getBoundingClientRect(); | |
var docElem = document.documentElement; | |
return ( | |
rect.top >= 0 && | |
rect.left >= 0 && | |
rect.bottom <= (window.innerHeight || docElem.clientHeight) && | |
rect.right <= (window.innerWidth || docElem.clientWidth) | |
); | |
} | |
var executeCallback = (function() { | |
var wasExecuted = false; | |
return function() { | |
if (!wasExecuted && isOnViewport(dom_element)) { | |
wasExecuted = true; | |
callback(); | |
} | |
}; | |
})(); | |
window.addEventListener('scroll', executeCallback, false); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment