Salesforce, Python, SQL, & other ways to put your data where you need it

Need event music? 🎸

Live and recorded jazz, pop, and meditative music for your virtual conference / Zoom wedding / yoga class / private party with quality sound and a smooth technical experience

Responsive, accessible navigation 7: Javascript on/off

10 Feb 2021 🔖 jamstack web development
💬 EN

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.

Screenshot of JavaScript flipping the DOM to js while the source says no-js

_(See the GitHub commit)

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).

Screenshot, items stacked & centered, narrow screen, JS on

Screenshot, items side-by-side, wide screen, JS on

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!

Screenshot, items stacked & centered, wide screen, JS off

(See the GitHub commit)

--- ---