JSFiddle - React, Tailwind, and code Playground
HTML
<h1>
scroll down
</h1>
<div class='spacer'></div>
<div id='target'>
<h2>
As soon as I come into view an alert will fire, but only once!
</h2>
</div>
<div class='spacer'></div>
CSS
.spacer {
background: #ccc;
height: 1200px;
}
JavaScript
var triggerAtY = $('#target').offset().top - $(window).outerHeight();
$(window).scroll(function(event) {
// #target not yet in view
if (triggerAtY > $(window).scrollTop()) {
return;
}
alert('I shall say it once, but only once');
// remove this event handler
$(this).off(event);
})
var counter = 0;
$(window).scroll(function(event) {
console.log('I\'m expensive', $(window).scrollTop(), ++counter);
});