Five Basic Things About JavaScript That Will Help Non JavaScript-Focused Web Designers
Five Basic Things About JavaScript That Will Help Non JavaScript-Focused Web Designers êŽë š
Letâs say you donât know JavaScript.
Like, at all.
You havenât needed it. Youâre a web designer and youâre focused largely on UI and UX. Your skills with design tools, HTML, CSS, and team communication have served you well.
But you know what JavaScript is. Itâs another part of the native web. Itâs powerful. It can make websites do stuff beyond what HTML and CSS can do alone. You donât even care to deeply learn JavaScript, you just want to get a ton of bang for the buck and learn things that will help you do your existing job better.
Letâs look at some things you could learn in a day that will give you that bang for the buck.
Weâre going to look at JavaScript code from here on out. But just so I donât lose anyone, let me make clear where you would put this JavaScript code to make it work. Youâre put it at the bottom of the HTML of the page youâre working on, before the closing </body>
tag, put a <script> /* you're code here */ </script>
. That code will run when any URL that uses that HTML loads.
If youâre writing a lot of it, or want to apply it to multiple HTML documents, you could also do <script src="./script.js"></script>
and put the JavaScript code in there. That references a file called script.js
that you would make and put next to the HTML.
Also, a lot of this code will run in the DevTools console in any of the browsers, so you could copy and paste it into there and hit Enter to try it.
1) Learn to Select Things
In JavaScript, you often want whatâs called a reference to an element. That is, a variable that represents the element in the DOM youâre trying to do something with.
Believe it or not, youâre at a real advantage here. Since you already know some CSS, those selectors are exactly what JavaScript can use to get itâs hands on those elements.
Say you had HTML like:
<header id="site-header">
<h1 class="logo">My Website</h1>
</header>
If you wanted a reference to that <header>
element, do it like this:
const header = document.querySelector("#site-header");
The "string"
inside that querySelector()
function is essentially the same as the CSS selector #site-header
.
If you wanted the logo, you could do:
const logo = document.querySelector(".logo");
You might be thinking to yourself: but CSS classes might apply to lots of elements, how does it know which one to get? The querySelector
function will select the first one it finds as it starts looking from the top of the HTML. If you intentionally want to look for and get a reference to a whole set of elements, look at querySelectorAll()
2) Learn to Update Classes (i.e. Toggle Stuff)
#1 is a big concept, but it doesnât actually do anything, it just helps you get those element references. Now letâs enact a real change. Letâs add a class to that header element weâve got.
header.classList.add("dark");
That does exactly what it looks like. It adds a class to that <header>
element, so now the HTML (the âDOMâ, really) will be like this:
<header id="site-header" class="dark">
<h1 class="logo">My Website</h1>
</header>
As an HTML and CSS person, I imagine you can feel the power here. You can change any styling you want when youâve got a class name you can select and use.
In fact, think about how you can change classes all the way up on the <html>
element. A class there means, through the power of CSS, you can change the style for anything on the page. As a neat bonus, you donât even have to querySelector
for the <html>
element. JavaScript automatically has a reference to it available.
document.documentElement.classList.add("paying-user");
That classList
API allows you to add, remove, replace, and toggle classes, as well as check to see if an element contains a certain class, so youâve got a lot of control there.
element.classList.add("javascript-enabled");
element.classList.remove("loading");
element.classList.replace("cat-lover", "dog-lover");
element.classList.toggle("open");
element.classList.toggle("raining", weather === "rain");
3) Learn to Listen for Events (e.g. Scroll, Click, and Change)
Selecting elements and changing classes is powerful, but itâs very likely youâre going to want to do that when something happens. The when in JavaScript is often an event. Itâs another API that allows us to âlistenâ for events. Events are happening all the time! Itâs our job to respond to them when they happen.
The click
event is the ultimate classic. Youâll want to attach click
events to elements that can receive focus. A <button>
, for example, is perfect. You can attach a click âhandlerâ to a <div>
, but itâs a bad choice as a <div>
isnât focusable. Many users use their keyboard only to navigate the web and may rely on screen readers to interact with it, and would be unable to âclickâ a <div>
with a click hander.
Imagine our header has a button in it:
<header id="site-header">
<h1 class="logo">My Website</h1>
<button>Switcheroo</button>
</header>
First we get a reference to that button, then add our click handling function:
const button = document.querySelector("button");
button.addEventListener("click", () => {
/* Code in here will run when the button is clicked */
console.log("Button was clicked!");
});
Hopefully that code above is clear. We selected the button, and we added an event listener for the event type click
. Donât worry much about the rest of the syntax for now, but just know that code within those { }
âcurly bracesâ will run when that button is clicked.
I slipped a little bonus in there for you: console.log()
. This little beautiful function allows you to send messages to the browser DevTools. If I have those DevTools open (Cmd/Control+Option+J) I can see the message output there, which is a nice âsanity checkâ that things are working.
You can send just about anything to console.log()
inside those parenthesis. Try selecting an element and putting the variable name in there.
Inside our new { }
in that âclick handler functionâ, we could do the job we already know how to do: update a class.
CodePen Embed Fallback
I know that end result feels rather basic, but I hope it demystifies JavaScript a bit for you. In a sense, weâre just doing these three things:
- Select
- Listen
- Update
4) Change HTML
Changing the class
of an element is changing the HTML of that element. But weâre not limited to that! We can quite literally change anything about it. Letâs assume element
is a reference to an element like we learned in #1. We could:
element.innerHTML = "<div>I'm now the entire guts of the element!!!</div>";
element.remove(); // Totally gone
element.dataset.version = "1.0.0"; // <element data-version="1.0.0">
element.style.backgroundColor = "red"; // <element style="background-color: red;">
element.insertAdjacentHTML("afterbegin", '<i>Hello</i>'); // <element><i>Hello</i> ...
Those are just some of the many powerful things you can do to HTML once you grab ahold and get a reference to an element.
5) Grab the values out of Form Elements
We already know how to select elements, and itâs no different for form elements. Say we have a form element like:
<label>
Size
<input type="range" id="size" ... >
</label>
Letâs:
- Select it
- Watch it for changes
- Do something when it does
// 1
const sizeSlider = document.querySelector("#size");
// 2
sizeSlider.addEventListener("input", (e) => {
// 3
wrapper.style.border = ` ${e.target.value}px solid black`;
});
Now that you can grab stuff from naturally interactive elements on the page, that should open some doors!
CodePen Embed Fallback
As an exercise, consider a password field like this:
<form id="form">
<label>
Password
<input type="password" id="password">
</label>
</form>
You can watch when the form is submitted, then check the password.
const form = document.querySelector("#form");
const passwordInput = document.querySelector("#password");
form.addEventListener("submit", (e) => {
e.preventDefault();
if (passwordInput.value === "") {
// User submitted empty password
} else if (passwordInput.value === "password") {
// User submitted correct password
} else {
// User submitted incorrect password
}
});
What UI/UX things might you want to do when doing this kind of interactive work? Perhaps you could âshakeâ the form on incorrect passwords. Maybe you could insert some HTML telling them the password was incorrect and they have X tries left. Maybe you could change colors. As a designer, youâll likely know exactly what you want to do, and now the page is interactive enough to properly prototype it.
Bonus: Design mode
This is a little bonus one:
document.designMode = "on";
This is probably most appropriate as a snippet to put in the DevTools console as a one-off, as having it always on would be weird. When this âmodeâ is on, every element on the page is editable. The text content of it, anyway.
More:
- If you want parts of a page to be editable (that arenât already form elements), you can always put
contentEditable
on them. - Just poking around and changing stuff like styles and content in DevTools is essentially doing the same things (behind the scenes) as weâve learned so far: manipulating the page with JavaScript.
- If youâre really into editing websites as they are in the browser as a design tool, check out more elaborate tools like VisBug.
Extra Credit: HTML Web Components
A Web Component (can be) an element in HTML you just⊠make up. The point of them is that they do something useful and you re-use them all over your site as needed. The name in them just has to have at least one dash:
<add-rainbows>
<div>
HTML in here that doesn't *need* rainbows, but would like them.
</div>
</add-rainbows>
These are a native part of the web platform and can be used no matter what other technology you use to build the site, making them universally useful. If you learn this, which I feel are just as useful for purely UI reasons as they are for anything else, you can bring the idea of components to your HTML work just as you likely already do in your design work. Designers building re-usable components is a world Iâd like to see.
Hereâs a silly example where the only job this Web Component has is to inject a <style>
tag into itself that styles itself.
CodePen Embed Fallback
Think: âA small, re-usable bit of styling and/or functionality that wraps a bit of otherwise perfectly usable HTMLâ. Jeremy Keith listed some examples recently:
jgarber623/aria-collapsible
 for toggling the display of one element when you click on another.daviddarnes/play-button
 for adding a play button to anÂaudio
 orÂvideo
 element.- ChrisâsÂ
ajax-form
 for sending a form via Ajax instead of a full page refresh.- JimâsÂ
user-avatar
 for adding a tooltip to an image.zachleat/table-saw
 for making tables responsive.
Discussion
Are you in this position yourself? Was this helpful? Or are there other things in JavaScript that youâd prefer to learn? Have you gone through this yourself already? What kind of things were the very first things you learned in JavaScript that were helpful?