Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sticky div on scroll with plain javascript

I wrote this sticky div effect in Jquery but was wondering a way to do the same thing with vanilla javascript

.stick {
    position: fixed;
    top: 0;
}



$(document).ready(function () {  
  var top = $('#a8').offset().top;
  $(window).scroll(function (event) {
    var y = $(this).scrollTop();
    if (y >= top)
      $('#a8').addClass('stick');
    else
      $('#a8').removeClass('stick');

  });
});
like image 435
Alex Borsody Avatar asked Jun 13 '26 06:06

Alex Borsody


2 Answers

Sure you can do the same in pure JS. Here is simple example:

var top = document.getElementById('a8').offsetTop;

window.onscroll = function() {
    var y = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
    if (y >= top) {
        a8.className = 'stick';
    }
    else {
        a8.className = '';
    }
};

Demo: http://jsfiddle.net/hd3uyf68/1/

Note, that in this simple example I don't actually implement addClass/removeClass functionality. If you need it it's quite easy to add.

like image 190
dfsq Avatar answered Jun 14 '26 18:06

dfsq


In vanilla JavaScript:

function ready() {
    var box = document.getElementById('box'),
        top = box.offsetTop;

    function scroll(event) {
        var y = document['documentElement' || 'body'].scrollTop;

        if (y >= top) box.classList.add('stick');
        else box.classList.remove('stick');

    }

    window.addEventListener('scroll', scroll);
}

if (document.readyState == 'complete' || document.readyState == 'loaded') {
    ready();
} else {
    window.addEventListener('DOMContentLoaded', ready);
}

JSFiddle example:

http://jsfiddle.net/869fqgds/4/

like image 28
Miguel Mota Avatar answered Jun 14 '26 20:06

Miguel Mota



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!