NUS Hackers Wiki
NUS Hackers Wiki
  • NUS Hackers Wiki
  • Hackerschool
    • Virtual Machines and Linux
    • Beginners' Guide to the Terminal
      • Introduction to the Terminal
      • Modern Shell Tools
      • Shell Scripting
      • Real World Scripting
      • Resources
    • Self-Hosting: Three Easy Pieces
      • 1. Setting up your server
      • 2. Running Services
      • 3. Monitoring your server
    • Vim
    • Introduction to Zig
      • Language Basics
      • Error Handling
      • Memory Management
      • Working with C
      • Exploring comptime
    • CI/CD with Github Actions
      • Background
      • Basics of Github Actions
        • Target workflow
        • Running unit tests
        • Linting code
        • Deploying to Github Pages
      • Advanced use cases
        • Pollers
        • Github script
        • Executing third-party scripts
        • Reusable workflows
      • Cookbook
    • Lightning Git
      • Git Concepts
      • Getting Started with Git
      • Making your first commit
      • Branching
      • Merge Conflicts
      • Integrating remote repositories
      • Collaborative Workflows
      • Commit Manipulation and Reflog
      • Interactive rebasing
      • filter-repo
  • Orbital
    • JavaScript
      • Browser Developer Tools
      • Getting Started
      • Datatypes
      • Operators and Operations
      • Loops and Conditions
      • Functions
      • Strings
      • Arrays
      • HTML
        • Getting Started
        • Tag Attributes
        • HTML Forms
        • Browser Inspector
      • CSS
        • Selectors
        • Colors in CSS
        • Measurements in CSS
        • The Box Model
        • Adding Styles - Part 1
        • Adding Styles - Part 2
      • Working with the DOM
        • Querying the DOM - Selectors
        • Querying the DOM - Element Attributes
        • Querying the DOM - Element Styles
        • Events with JS and HTML
        • Exercise: Click Counter
        • Editing the DOM
        • Fetch Requests
        • Exercise: The NUSMods API
    • React
      • Setup
      • State
    • React Native
      • Setup
      • Intro to JSX
      • Basic Syntax
      • Handling UI
      • Props
      • State Management
    • Git
      • Setup
      • Command Glossary
      • Fundamental Concepts
        • Getting Started
        • Integrating Remote Repositories
        • Branching
        • Merge Conflicts
      • Collaborative Workflows
        • Fork and PR Workflow
        • Branch and PR Workflow
      • Advanced Concepts
        • Ignoring Files
        • Commit Message Conventions
        • Github Collaborators
        • CI/CD with Github Actions
        • Advanced Git Commands
      • FAQ
    • Telegram Bot
      • Creating a TeleBot
      • API Calls
      • Telebot Basics
      • Integrating API's
    • Relational Database
      • Database Overview
      • Database Design
      • Entity Relationship Diagram
      • SQL Basics & PostgreSQL
    • TypeScript
      • Types and Interfaces
      • Utility Types
      • Typing Component Props, Events, and Hooks
      • Why You Should Avoid Using any (and What to Do Instead)
      • TypeScript Tricks You’ll Use All the Time in React
Powered by GitBook
On this page
  • Set up the html file
  • The script
  • Adding an event listener
  • updateCounter function
  • Test it out
  • Bonus (try it yourself)
  • Next steps
Edit on GitHub
Export as PDF
  1. Orbital
  2. JavaScript
  3. Working with the DOM

Exercise: Click Counter

Note: We will use the same HTML page we have been using. I'll refer to it as clicker.html.

In this section, we'll make a simple page that has a button and a counter. Each time the button is clicked, the value of the counter is incremented. We'll use the same page we have been using before.

Set up the html file

Set up the html file such its body contains at least the following two items:

  • a button with an id

  • a text element of your choice also with an id

An example is below:

<body>
    <p id="counter">0</p>
    <button id="trigger">Click me</button>
</body>

You can have other elements and other styling to make it nicer, but that is up to you.

The script

Adding an event listener

Add an event listener to the script.js file that listens for the DOM content to be loaded, upon which it adds an event listener to the button. Here's how that looks:

document.addEventListener("DOMContentLoaded", function() {
    let button = document.getElementById("trigger");
    button.addEventListener("click", updateCounter);
});

updateCounter is the function that we will use to update the counter on the page.

updateCounter function

Inside this function we need to do the following:

  1. Get the counter element from the page

  2. Get its text value

  3. Increment it by 1

  4. Set the counter element's inner value to the new value

Try doing this yourself before looking at the code below.

Note that an element's inner text is always returned as a string, so you need to convert it to an integer. This can be done with the parseInt function:

parseInt("4324"); // returns 4324
function updateCounter() {
    // query for the element
    let counterElement = document.getElementById("counter");
    // get the counter value
    let count = parseInt(counterElement.innerText);
    // increment the counter value
    count++;
    // set the counter value
    counterElement.innerText = count;
}

Test it out

That's all we had to do. Now, test out the code by saving all files, reloading the page, and then clicking the button. The counter value should get incrememented:

Bonus (try it yourself)

Try adding the following features:

  1. When the counter value reaches a non-zero multiple of 10, its font color should change to gold, and set back to original color otherwise

  2. Add a second button that resets the counter variable to 0

  3. Add a third button that decrements the counter, but no longer decreases after reaching 0.

Next steps

Next we'll look at how elements can be created or removed in a page.

PreviousEvents with JS and HTMLNextEditing the DOM

Last updated 12 months ago

A sample solution can be found .

here