HTML and CSS are the most resilient parts of the front end, so you should always lean on them where possible. There are times, though, when you should prefer JavaScript. Here are a few examples.

Use HTML and/or CSS

A couple of weeks ago, I was working on a project for the Vanilla JS Academy. It's a script that uses the New York Times API to get and display today's top stories across multiple categories.

I needed to display each category in titlecase. My first thought was to use a helper function to convert the strings. And then I realized...

Duh! I can do this with CSS! 🤦‍♂️

All I needed to do was add a class to each category:

.category {
text-transform: capitalize;
}

This is so much easier and more robust than using JavaScript.

You can view the project on CodePen.

Use JavaScript

Pure HTML form validation

It's possible to validate your forms on the client side using pure HTML.

As explained in the MDN Web Docs:

One of the most significant features of HTML5 form controls is the ability to validate most user data without relying on JavaScript. This is done by using validation attributes on form elements.

Unfortunately, it's not quite up to scratch for accessibility (A11Y).

Instead, I recommend using Bouncer. It's a lightweight plugin that augments the native validation elements and attributes. It just works, out of the box, with all the necessary ARIA behaviours baked in.

IMPORTANT: You must always validate your forms on the server. Never rely on client-side validation alone.

Pure CSS lightbox

It's possible to use the :target pseudo-class to create a pure CSS lightbox.

It sure is cool that this is possible, but I wouldn't use it. It works for mouse users, but not keyboard users. There are a lot of A11Y considerations for something like a modal dialog.

Instead, I would use tried and tested plugins that have these A11Y considerations baked in.

In this scenario, I would use the Accessible Modal Dialog by Scott O'Hara.

Summary

Generally speaking, if you can implement something with HTML and CSS, then you should. Don't add unnecessary JavaScript.

There are times, though, when you should prefer a JavaScript solution. This is usually for design patterns with known A11Y concerns, such as modal dialogs and image slideshows.

For more information, I recommend the following resources: