Skip to content
Tutorials Center
My learning

Topics

Lesson 130 of 156 Β· Projects

Project: Five Mini DOM Apps

Build five small DOM apps in plain JavaScript: a counter, a password generator, a show/hide password field, a palindrome checker and an image carousel.

Big projects teach architecture. Small projects teach habits. In this lesson you will build five tiny apps, each one a single page of HTML, CSS and JavaScript that you can finish in a few minutes. They look simple, but each hides one or two details that separate a quick demo from something you could ship: keyboard support, screen-reader announcements, secure randomness, Unicode text and respect for users who don't want motion.

Each app is complete on its own, so you can do them in any order. Run it, play with it, then read the code and the notes below it. Try to change one thing in every app before you move on β€” that is where the learning sticks.

What you'll build

  1. Counter β€” plus, minus, a step size, limits and keyboard shortcuts.
  2. Password generator β€” length and character options, real cryptographic randomness and a strength estimate.
  3. Show/hide password β€” a toggle button, a Caps Lock warning and live password rules.
  4. Palindrome checker β€” text normalization with Unicode-aware regular expressions.
  5. Image carousel β€” previous/next, dots, autoplay that pauses, swipe and reduced motion.

A bonus section adds four more small widgets: toast notifications, pagination, a star rating and a range slider. A second bonus section adds four small games: word scramble, coin flip, hit the mouse and memory.

You will use ideas from Selecting Elements, Events, Bubbling, Capturing and Delegation, Styles and Classes, Timers and Regular Expressions.

One pattern for all five

Every app below follows the same three-part shape that the to-do app used:

  1. State β€” a few variables hold the truth (the count, the current slide, whether the password is visible).
  2. render() β€” one function makes the page match the state.
  3. Handlers β€” events only change the state, then call render().

In tiny apps this can feel like overkill, since you could just set textContent inside the click handler. But as soon as a second control affects the same display (a keyboard shortcut, a reset button, a timer), having exactly one place that updates the page saves you from "the button says one thing, the screen says another" bugs.

App 1: A counter with limits

A counter is the "hello world" of interfaces. This one adds the details people actually notice: a selectable step, a range it can't leave, a different color for negative numbers and keyboard shortcuts.

App 1: Counter

Three details are worth stealing for your own projects:

  • clamp() keeps the value in range in one line. With a step of 10, going up from 45 lands on exactly 50 instead of overshooting to 55. Because every change goes through move(), no path can sneak past the limit.
  • aria-disabled instead of disabled. A real disabled button can't keep focus. If a keyboard user keeps pressing Enter on + until the counter hits 50, a disabled button would drop focus to the page body and they would lose their place. aria-disabled="true" tells assistive technology the button is unavailable, the CSS dims it, and the handler ignores clicks, but the focus stays put.
  • <output aria-live="polite">. <output> is the HTML element for "a result of a user action", and the live region makes screen readers announce the new value after each change.

The keyboard handler ends with event.preventDefault() only for keys it handled. The trick is the else return; line: any other key leaves the function before reaching preventDefault(), so Tab and every other key still work normally.

App 2: A random password generator

A password generator must be unpredictable, and Math.random() is not designed for that. Its output is fast and evenly spread, but it is not meant to resist someone trying to predict it. For anything security-related, use crypto.getRandomValues(), which fills a typed array with cryptographically strong random numbers (see Typed Arrays).

App 2: Password generator

The interesting part is randomInt(). The obvious version, buffer[0] % max, is slightly unfair. A Uint32Array value is one of 2Β³Β² numbers, and 2Β³Β² is not a multiple of most pool sizes, so the first few characters of the pool would come up a tiny bit more often. The fix is called rejection sampling: compute the largest multiple of max that fits, and if the random number lands in the leftover tail, throw it away and draw again. That rarely needs more than one try.

The rest of the generator is built from small pieces:

  • One of each, then shuffle. If you just pick 16 characters from the whole pool, a password with "digits" ticked can still contain no digit. Picking one character from every chosen set first guarantees each one, and the Fisher–Yates shuffle (also using randomInt()) hides where they are.
  • Strength in bits. Each character chosen from a pool of N symbols adds logβ‚‚(N) bits of randomness. Sixteen characters from 62 letters and digits give about 95 bits, far beyond what anyone can guess. This estimate is honest only because the password is truly random. A human-chosen "P@ssw0rd!" has far less strength than its length suggests.
  • input on the form. One listener on the <form> catches changes from the slider and all five checkboxes, because input events bubble.
  • The clipboard fallback. navigator.clipboard needs a secure context and permission, and the TryIt preview runs in a sandbox without it. Instead of failing silently, the code selects the password and tells the user what to press. In your own HTTPS site, the first branch runs and Copy just works.

App 3: Show and hide a password

Typing a long password blind leads to typos, especially on phones. A Show button lets people check what they typed. This version also warns when Caps Lock is on and checks a few sensible rules as the user types.

App 3: Show/hide password

How the pieces fit:

  • Switching type between "password" and "text" is the whole trick. The value stays the same, so nothing is lost.
  • aria-pressed turns the button into a toggle button. Screen readers announce "Show, toggle button, not pressed", and the visible label changes too. aria-controls links the button to the field it affects.
  • getModifierState("CapsLock") reads the Caps Lock state from any keyboard event. Checking on keydown and keyup catches the moment the user presses Caps Lock itself. The warning is part of aria-describedby, so it is read along with the field.
  • Rules as a lookup table. Each <li> names its rule in data-rule, and RULES maps the name to a test function. Adding a rule means adding one <li> and one function.
  • setCustomValidity() hooks the rules into the browser's own validation. Until every rule passes, pressing Sign up shows the browser's message instead of submitting (see Working with Forms).

The rules themselves follow current security advice: length matters most, and forcing "one uppercase, one digit, one symbol" mostly produces predictable passwords like Summer2026!. Real sign-up forms also check the password against lists of leaked passwords on the server, which is something a front-end check can't do.

Hide the password again before the form submits. Some password managers only offer to save a field while it is type="password", and a password left visible on screen is easy to read over someone's shoulder.

App 4: A palindrome checker

A palindrome reads the same forwards and backwards: "level", "Step on no pets", "Never odd or even". The interesting part isn't the reversal β€” it's deciding what counts as the same. Spaces, punctuation, upper and lower case and accents should all be ignored. Start with the logic alone, in the console:

JS Normalizing text before comparing

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The table shows the first five samples as palindromes. "JavaScript" isn't one, and "?!" gives false because nothing is left after cleaning β€” an empty string shouldn't count as a palindrome.

Each step in normalize() has a job:

  • normalize("NFD") splits accented letters into a base letter plus a separate combining mark, so "Γ‰" becomes "E" followed by an accent.
  • /\p{M}/gu removes those marks. The u flag turns on Unicode property escapes like \p{M} (marks), \p{L} (letters in any script) and \p{N} (digits) β€” see Regex in Practice.
  • [^\p{L}\p{N}] matches everything that is not a letter or digit, so spaces and punctuation vanish, but letters from Greek, Cyrillic or Arabic text survive. The older [^a-z0-9] would wipe them out.

The last two lines show why the function uses Array.from(). An emoji like πŸ˜€ is stored as two UTF-16 code units (a surrogate pair, see Strings). split("") cuts it in half, and reversing swaps the halves into garbage. Array.from() splits by code point and keeps it whole. Emoji built from several code points (skin tones, flags, families) need Intl.Segmenter to split by what users see as one character.

Now wrap the logic in a page. It checks as you type and shows the cleaned text, highlighting the first pair of characters that don't match:

App 4: Palindrome checker

Note how the highlighted text is built from DOM nodes (createTextNode() and <mark> elements) rather than an HTML string. The user typed this text, and building it with innerHTML would let typed <img onerror=…> run as code β€” the Security lesson explains why textContent and DOM nodes are the safe default. Clicking an example button reuses render(), so there is still only one place that updates the page.

Carousels look easy and are notoriously hard to get right: autoplay that never stops, slides you can't reach with the keyboard, motion that makes some people feel sick. This one starts from plain HTML slides (the content works even if JavaScript fails) and adds:

  • previous/next buttons, dot buttons and the ← β†’ keys;
  • autoplay every 4 seconds that pauses while the pointer or focus is inside, plus a Pause/Play button;
  • swiping on touch screens with pointer events;
  • no animation and no autoplay for people who set "reduce motion" in their system.
App 5: Image carousel

Here is what makes this carousel better than most:

  • Wrapping with %. (i + slides.length) % slides.length turns βˆ’1 into the last slide and 4 into the first, so previous and next never run off the end. Adding slides.length first matters, because in JavaScript -1 % 4 is -1, not 3.
  • inert on hidden slides. The slides are only moved out of view with transform, so without inert, Tab would happily walk into invisible links. Setting slide.inert = true makes a slide and everything inside it unfocusable and hidden from assistive technology.
  • Separate flags for playing. playing is the user's choice (the Pause/Play button). hovering and keyboardInside are temporary pauses. Autoplay runs only when all three allow it, and restartTimer() is the one place that starts or stops the interval. Keyboard focus is detected with :focus-visible, which matches after Tab but not after a mouse click, so clicking Play doesn't leave the carousel paused. The focusout check with relatedTarget ignores focus moving between the carousel's own buttons.
  • Reduced motion. matchMedia("(prefers-reduced-motion: reduce)") reads the user's system setting. For those users, the CSS media query removes the sliding animation and autoplay is off from the start.
  • aria-live only for manual changes. A live region that announces a new slide every 4 seconds would talk over everything else, so the track is aria-live="off" while playing and "polite" when the user is in control.

To use real photos, put an <img> with good alt text in each slide instead of the inline SVG, and add loading="lazy" to every image except the first, so slides the user never reaches are never downloaded.

Bonus: four small UI widgets

Once the five apps feel comfortable, here are four more widgets that appear on nearly every site: a toast notification, pagination, a star rating and a range slider. They are shorter than the apps above, and each one teaches a different lesson: timers you can pause, a pure function that does the hard thinking, using native form controls instead of replacing them, and driving CSS from JavaScript through a custom property.

Widget 1: Toast notifications

A toast is a small message that appears, stays a few seconds and leaves by itself ("Saved", "Copied to clipboard"). Three details separate a good one from an annoying one:

  • It lives in a polite live region (role="status"), so screen readers announce it without interrupting. The container must exist in the page before you add toasts, or some screen readers miss the first message.
  • It pauses while the pointer is over it or focus is inside it, so nobody loses a message they were reading. That means tracking the remaining time, not just starting a timer.
  • It has a close button, because a message that vanishes by itself must still be dismissable by someone who wants it gone now.
Widget 1: Toasts that pause on hover

Press the buttons quickly: only three toasts are kept (MAX_TOASTS), and the oldest is removed first. Hover one and wait: the timer stops, and it resumes with the time that was left, because pause() subtracts the elapsed time from remaining. Errors stay longer than successes, since people need more time to read what went wrong.

Never use a toast for something the user must act on, such as a failed payment. Disappearing messages are easy to miss, and they cannot hold a button the person needs to press. Use an inline message or a dialog for those.

Widget 2: Pagination

Pagination splits a long list into pages. The trick is the row of page numbers. With 40 pages you cannot show all the buttons, so you want something like 1 ... 5 6 7 ... 40: always the first page, the last page, and a few pages around the current one.

That logic is a pure function, so write and test it without touching the page. pageList(current, total) returns an array of numbers and "..." markers. The rendering code then turns each entry into a button or a gap.

JS Widget 2: The page-list function

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first and last pages are always present, and the window around the current page slides along. Near either end the window turns into a block of consecutive pages with a single ..., so the row always has the same number of entries (seven here) and the buttons do not jump around as you click. Try a larger siblings value for a wider window.

Now the widget. It slices the data for the current page and rebuilds the number row from pageList(). The current page gets aria-current="page", which is both the accessibility signal and the CSS hook, and Previous/Next are disabled at the ends.

Widget 2: Paginated list

Switch to 5 items per page to get ten pages, then click through them and watch the window slide. Changing the page size sends you back to page 1, because page 6 at 8 per page is not the same place as page 6 at 12 per page. The Math.min(Math.max(page, 1), total) line clamps the page, so a bad value (0, or a page past the end after the size changes) can never produce an empty screen.

Widget 3: Star rating

You could build a star rating from five <span> elements and click handlers, but then keyboard users and screen readers get nothing. The better idea is to use what the browser already provides. A group of radio buttons gives you a single choice, arrow-key navigation, a form value and a screen-reader description for free. JavaScript only adds the look: filling stars up to the chosen value and previewing the value under the pointer.

Widget 3: Accessible star rating

Click a star, then use Tab to focus the group and the arrow keys to change the rating. No extra code handles that, because radio buttons already do. In a real form, new FormData(form).get("rating") returns the chosen value, so the widget submits like any other field. The aria-label on each input gives a screen reader "4 stars: Good", where the visible β˜… character would otherwise be read as "black star".

Widget 4: Range slider with a live value

<input type="range"> is already an accessible slider with keyboard support. What it lacks is a visible value and a filled track. Both come from small bits of JavaScript: an <output> element that mirrors the value, and a CSS custom property, --pct, that holds the thumb position as a percentage so the stylesheet can paint the fill.

The second control shows a different problem: a minimum and maximum price pair, where the minimum must never pass the maximum. That rule lives in one function.

Widget 4: Sliders

Drag the volume thumb and watch the number and the blue track follow it: percent() turns the value into a position, and the stylesheet does the painting through var(--pct). Then drag Minimum above Maximum: the thumb stops at the maximum, because clampPair() pushes back whichever slider you moved.

Three ideas carry over to any custom control:

  • Start from a native element (range, radio, button, dialog) and enhance it. You inherit keyboard behavior, forms and accessibility.
  • Put the rules in one small function (pageList(), clampPair(), percent()) so event handlers stay thin.
  • Let CSS draw and JavaScript supply numbers. Custom properties such as --pct are the cleanest bridge between the two.

Bonus: four small games

Games are a fun way to practice the same skills: a state object, a render() function, timers and good randomness. Each one below is short and playable, and each hides one lesson that applies far beyond games.

Game 1: Word scramble

The computer picks a word, shuffles its letters and you type the original. The key function is the shuffle. A sort with a random comparison (array.sort(() => Math.random() - 0.5)) is a well-known trap because it is biased and inconsistent; use the Fisher–Yates shuffle from the password generator instead. Shuffling can also return the original word by chance, so loop until the result differs. Compare answers after trimming and lower-casing.

Game 1: Word scramble

A hint costs one point, so a correct answer is worth 2 points, or 1 with a hint. The message element has role="status", so a screen reader hears "Correct!" without focus leaving the input.

Game 2: Coin flip

A fair coin is a one-line function, but it is a good place to see how small details add up. Math.random() < 0.5 is fine for a game (never use it for secrets; see the password generator above). The tally and history use a plain object as state, and the animation is a CSS class that is re-triggered on each flip.

Game 2: Coin flip with a tally

With only a few flips the split is rarely exactly 50/50. That is normal, and the percentages drift toward 50% as the count grows. The void coin.offsetWidth line is the classic trick for restarting a CSS animation: removing and re-adding a class in the same frame does nothing, but reading a layout property forces the browser to notice the removal first.

Game 3: Hit the mouse

Mice pop up in a 3 by 3 grid for twenty seconds; click as many as you can. It combines two timers: a game clock that counts down every second and a spawn timer that moves the target. The important habit is cleaning up: every setInterval must be stopped when the game ends, or old timers keep running and a second game would have two timers moving the mouse.

The target never appears in the same hole twice in a row, which feels fairer. Clicks use one delegated listener on the board (see Bubbling, Capturing and Delegation), and a hit hides the target immediately so a double click cannot score twice.

Game 3: Hit the mouse

end() clears both intervals, and the Start button is disabled while a game runs. A common bug is starting a second game on top of the first one; the disabled button plus the cleanup makes that impossible.

Game 4: Memory (matching pairs)

Twelve face-down cards hide six emoji pairs. Flip two: if they match they stay open, otherwise they flip back after a moment. Three rules make this game work:

  1. Shuffle once at the start with Fisher–Yates.
  2. Lock the board while two mismatched cards are showing. Without the lock, a fast player can flip a third card and break the state.
  3. Keep the truth in data, not in the DOM: every card is an object { symbol, open, matched }, and render() draws it.

Cards are real <button> elements, so they work with the keyboard, and each has an accessible name that only says "Card 3, face down" until it is open.

Game 4: Memory

Because render() rebuilds the buttons, the one you just clicked is replaced and loses keyboard focus. In a production game you would move focus to the new button with the same data-index, exactly as the pager in the data table project does.

Games like these share a recipe: pure helper functions (shuffle, scramble), a small state object, one render(), and timers that are always cleaned up. That recipe scales to much larger games.

More ideas to try

  • Counter: hold down + to repeat, using pointerdown to start a setInterval and pointerup to stop it.
  • Password generator: add a "passphrase" mode that picks four to six random words from a list. With 2,048 words, each word adds 11 bits.
  • Show/hide: add a strength meter that turns red, amber or green as the password grows.
  • Palindrome checker: find the longest palindrome inside a sentence, not just whether the whole thing is one.
  • Carousel: show a thumbnail strip, and preload the next slide's image while the current one is shown.
  • Toast: add an "Undo" button inside a toast and run the undo callback if it is pressed before the toast leaves.
  • Pagination: keep the current page in location.hash so the browser Back button and shared links work.
  • Star rating: support half stars by doubling the scale to ten radio buttons and styling pairs of them as one star.

Check your understanding

Quick check Β· 7 questions

of 7 answered You scored / 7 Β· perfect!

  1. 1. Why does the password generator use crypto.getRandomValues() instead of Math.random()?

    Math.random() is fine for games and animations, but passwords, tokens and keys need values that can't be predicted, which is what the Web Crypto API provides.
  2. 2. Why does randomInt() draw again when the random number is at or above limit?

    Without rejection sampling, value % max would favor the first few values slightly. Throwing away the uneven tail removes that bias.
  3. 3. What does "πŸ˜€xπŸ˜€".split("").reverse().join("") === "πŸ˜€xπŸ˜€" evaluate to?

    Emoji outside the Basic Multilingual Plane are surrogate pairs. Array.from() splits by code point and keeps them whole.
  4. 4. Why does the counter use aria-disabled="true" instead of the disabled attribute at its limits?

    aria-disabled keeps the button focusable and tells assistive technology it is unavailable. The click handler has to ignore the click itself.
  5. 5. In the carousel, what does setting slide.inert = true on hidden slides achieve?

    Slides moved out of view with transform are still in the page. inert stops Tab from reaching anything inside them.
  6. 6. In the pagination widget, why is the list of page numbers produced by a separate pure function?

    pageList() only works with numbers, so you can check every edge case (first page, last page, few pages) by logging its results, while the DOM code just turns entries into buttons.
  7. 7. Why are the stars in the rating widget built from radio inputs?

    Starting from a native control means you inherit keyboard behavior and accessibility. JavaScript only adds the filled-star look and the hover preview.

Summary

  • Even tiny apps benefit from state β†’ render() β†’ handlers: every control and shortcut changes the state, and one function updates the page.
  • Keep values in range with a clamp() helper, and use aria-disabled when a control must stay focusable.
  • For anything secret, use crypto.getRandomValues() with rejection sampling, and a Fisher–Yates shuffle for unbiased ordering.
  • A show/hide toggle swaps type between password and text, uses aria-pressed, and getModifierState("CapsLock") powers a Caps Lock warning.
  • Compare text after normalizing it: normalize("NFD"), Unicode property escapes with the u flag, and Array.from() to split by code point.
  • An accessible carousel wraps with %, marks hidden slides inert, pauses on hover and focus, offers Pause/Play and honors prefers-reduced-motion.
  • Toasts live in a polite live region, pause their timer on hover and focus by tracking the remaining time, and always have a close button.
  • Pagination is a pure pageList() function plus clamping; star ratings and sliders are best built on native radio and range inputs, with CSS custom properties such as --pct carrying values from JavaScript to the stylesheet.
  • Small games reuse the same recipe: a state object, helper functions such as an unbiased Fisher–Yates shuffle(), one render(), a lock while a mismatch is showing, and timers (setInterval) that are always cleared when the game ends.

Next: Project: GitHub Profile Search