Skip to content

Instantly share code, notes, and snippets.

@elliotec
Created June 12, 2017 16:26
Show Gist options
  • Save elliotec/44a036e337d03abbc8a0653fa422783e to your computer and use it in GitHub Desktop.
Save elliotec/44a036e337d03abbc8a0653fa422783e to your computer and use it in GitHub Desktop.
componentDidMount() {
window.addEventListener('scroll', this.throttleGoogleAdScroll());
}
throttleGoogleAdScroll() {
// listen and throttle the scroll every second at start and end of scroll
return _throttle(this.handleShowGoogleAdsense,
1000,
{ trailing: true, leading: true }
);
}
handleShowGoogleAdsense() {
// check trigger element exists
if (document.getElementById('adsTrigger')) {
const adsTriggerScrollPosition = document.getElementById('adsTrigger').getBoundingClientRect().top;
// fire the action when the trigger is within 100px of the bottom of screen
if (__CLIENT__ && (adsTriggerScrollPosition) <= (window.innerHeight + 100)) {
this.props.onShowGoogleAdSense();
// stop listening after ads are shown
if (this.props.shouldShowGoogleAdSense) {
window.removeEventListener('scroll', this.throttleGoogleAdScroll());
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment