Joshua Waheed Joshua Waheed - 6 months ago 18
CSS Question

Position: Sticky effect with JavaScript

I'm trying to write a simple script with pure JavaScript, which creates a position sticky effect. The code below works well for me.

var siteHeader = document.getElementById('siteHeader'),
siteNav = document.getElementById('siteNav');

window.onscroll = function() {
if ( siteNav.offsetTop < document.documentElement.scrollTop + 26 || siteNav.offsetTop < document.body.scrollTop + 26) {
siteHeader.setAttribute("class","sticky");
}
else {
siteHeader.setAttribute("class","");
}
}


Is there a cleverer way of writing this line?

if ( siteNav.offsetTop < document.documentElement.scrollTop + 26 || siteNav.offsetTop < document.body.scrollTop + 26) {


I tried writing this but it doesn't seem to work the way I want it to.

siteNav.offsetTop ? document.documentElement.scrollTop + 26 : siteNav.offsetTop < document.body.scrollTop + 26


Apologies if the ternary condition looks stupid.

Answer

Using just the original code (amend from suggestions as you see fit...)

If you're only concerned about add/remove the "sticky" class...

siteHeader[siteNav < (document.documentElement || document.body).scrollTop + 26 ? "addClass" : "removeClass"]("sticky");

-- EDIT --
Didn't notice the siteHeader is selected with vanilla JS...

siteHeader.setAttribute("class", 
    siteNav < (document.documentElement || document.body).scrollTop + 26 
        ? "sticky" : "");

Now, "clever" vs. readability is entirely subjective, but the logic should fit.