eabates eabates - 10 months ago 59
jQuery Question

trigger on scroll past DOM element

I am trying to trigger actions when the user scrolls into various DOM elements (I need this to be responsive for various screen sizes). I first get the locations of the respective elements with

then I calculate the location of the scroll with
. It works somewhat but the action is triggered too far past the start of the DOM element. I have removed all padding and margins...

var hT = $('#bioAG').offset().top;
var hT2 = $('#bioTM').offset().top;
var hT3 = $('#contact').offset().top;

$(window).scroll(function () {
var ws = $(window).scrollTop()
if (ws > hT) {
} else if (ws > hT2){
} else if (ws > hT3) {
} else {console.log('none');};

}) `

Answer Source

On scroll (load and resize) calculate the .top position of every data-fadein elements.
filter() then returning the elements which top position is less than the window height - and add on that elements the desired class.

var $ele = $("[data-fadein]"),
    $win = $(window);

function fadeInEl() {

  var h = $win.height();

  $ele.filter(function() {
    return this.getBoundingClientRect().top < h;


// Call the above function on:
$win.on("load resize scroll", fadeInEl);

[data-fadein] {
  transition: 2s;
.fade-in {
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div data-fadein id="bioAG"   style="background:#0af">ag</div>
<div data-fadein id="bioTM"   style="background:#f0a">tm</div>
<div data-fadein id="contact" style="background:#0fa">contact</div>