JSFiddle - React, Tailwind, and code Playground
by Roko
HTML
<div id="box"></div>
CSS
/*QuickReset*/
* {
margin: 0;
box-sizing: border-box;
}
html,
body {
height: 100%;
font: 14px/1.4 sans-serif;
}
input,
textarea {
font: 14px/1.4 sans-serif;
}
body {
height: 4000px;
}
#box {
position: absolute;
height: 500px;
width: 100%;
top: 2000px;
background: red;
}
JavaScript
/**
* inViewport jQuery plugin by Roko C.B.
* http://stackoverflow.com/a/26831113/383904
* Returns a callback function with an argument holding
* the current amount of px an element is visible in viewport
* (The min returned value is 0 (element outside of viewport)
*/
;
(function($, win) {
$.fn.inViewport = function(cb) {
return this.each(function(i, el) {
function visPx() {
var eH = $(el).outerHeight(),
wH = $(win).height(),
r = el.getBoundingClientRect(),
t = r.top,
b = r.bottom,
data = { // <<< Create an object to return to callback
visibleHeight: Math.max(0, t > 0 ? Math.min(eH, wH - t) : (b < wH ? b : wH)),
rect: r,
height: eH,
windowHeight: wH
};
return cb.call(el, data); // <<< pass it as callback data
}
visPx();
$(win).on("resize scroll", visPx);
});
};
}(jQuery, window));
$("#box").inViewport(function(data) { // <<< now you can access your data
if (data.visibleHeight > 0) {
var bottomOff = (data.rect.bottom - data.windowHeight);
console.log(bottomOff);
// Your condition:
if (bottomOff < 200) {
console.log("AJAXXXXXXXX");
}
}
});