Responsive, accessible navigation 7: Javascript on/off
10 Feb 2021
Time to add some JavaScript to main.js
so I can design my CSS around whether it’s on or not.
// To indicate that JavaScript is turned on, replace the "no-js" class on the "html" element with "js" instead
(function (html) {
html.className = html.className.replace(/\bno-js\b/, "js");
})(document.documentElement);
Up in base.liquid
I’ll edit the <html>
tag to have a class of no-js
by default. This JavaScript, when a browser has JavaScript running, will replace it with js
.
To use it, I added some more SASS to _nav.scss
.
I’ve got a feeling that I’ll want a similar look and feel for both “small screens” and “large screens without JavaScript,” so I played with putting every navigation element on its own line in a SASS mixin called wide-nav-mixin()
.
I include this mixin in both html.no-js
and @media (max-width: ($width-md+60))
(somewhat narrow) screens.
@mixin wide-nav-mixin() {
.topnav__header,
.topnav__body,
.topnav__body__outeritem {
width: 100%;
}
.topnav__body__outeritem {
text-align: center;
}
}
html.no-js {
@include wide-nav-mixin();
}
@media (max-width: ($width-md+60)) {
@include wide-nav-mixin();
}
Resizing my browser window, I get a drastic flip at the 803px/804px window-size breakpoint (no idea why it isn’t 799px/800px like I’d expect – but close enough – I changed md
to sm
and it had the same “4 pixels too big” issue so at least it’s more-or-less doing what I said).
Also, when I take my browser window full-screen well above this breakpoint and comment out the JavaScript I wrote that flips no-js
to js
, or when I manually edit the DOM w/ the browser Developer Tools back to no-js
, I get the “centered stack.” So the CSS is working the way I want it to. Neat!