eabates eabates - 2 months ago 16
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

offset().top
then I calculate the location of the scroll with
scrollTop()
. 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) {
$("#bioAG").addClass("fade-in");
} else if (ws > hT2){
$("#bioTM").addClass("fade-in");
} else if (ws > hT3) {
$("#contact").addClass("fade-in");
} else {console.log('none');};


}) `

Answer

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;
  }).addClass("fade-in");

}


// Call the above function on:
$win.on("load resize scroll", fadeInEl);
*{box-sizing:border-box;}
html,body{height:100%;margin:0;}


[data-fadein] {
  height:100vh;
  opacity:0;
  transition: 2s;
}
.fade-in {
  opacity:1;
}
<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>

https://developer.mozilla.org/en/docs/Web/API/Element/getBoundingClientRect