JavaScript and HTML

Now that we've reviewed some of the tools for programming JavaScript, let's look at adding code to HTML and running it in a web browser. JavaScript is applied to your HTML page in a similar manner to CSS. Whereas CSS uses <link> elements to apply external stylesheets and <style> elements to apply internal stylesheets to HTML, JavaScript only needs one friend in the world of HTML: the <script> element. Let's learn how this works.

Use scripting accessibly

Accessibility is a major issue in any software development. JavaScript can make your website more accessible if you use it wisely, or it can become a disaster if you use scripting without care. To make JavaScript work in your favor, it's worth knowing about certain best practices for adding JavaScript:

  • Make all content available as (structured) text. Rely on HTML for your content as much as possible. For example, if you've implemented a nice JavaScript progress bar, make sure to supplement it with matching text percentages inside the HTML. Likewise, your drop-down menus should be structured as unordered lists of links.
  • Make all functionality accessible from the keyboard.
    • Let users Tab through all controls (e.g., links and form input) in a logical order.
    • If you use pointer events (like mouse events or touch events), duplicate the functionality with keyboard events.
    • Test your site using a keyboard only.
  • Don't set nor even guess time limits. It takes extra time to navigate with the keyboard or hear content read out. You can hardly ever predict just how long it will take for users or browsers to complete an process (especially asynchronous actions such as loading resources).
  • Keep animations subtle and brief with no flashing. Flashing is annoying and can cause seizures. Additionally, if an animation lasts more than a couple seconds, give the user a way to cancel it.
  • Let users initiate interactions. That means, don't update content, redirect, or refresh automatically. Don't use carousels or display popups without warning.
  • Have a plan B for users without JavaScript. People may have JavaScript turned off to improve speed and security, and users often face network issues that prevent loading scripts. Moreover, third-party scripts (ads, tracking scripts, browser extensions) might break your scripts.
    • At a minimum, leave a short message with <noscript> like this: <noscript>To use this site, please enable JavaScript.</noscript>
    • Ideally, replicate the JavaScript functionality with HTML and server-side scripting when possible.
    • If you're only looking for simple visual effects, CSS can often get the job done even more intuitively.
    • Since almost everybody does have JavaScript enabled, <noscript> is no excuse for writing inaccessible scripts.