Basic JavaScript Knowledge
A quick refresher on the HTML DOM and event listeners for anyone new to JavaScript.
This page covers some fundamental JavaScript concepts used across several tutorials. If you’re already comfortable with JavaScript, feel free to skip this. w3schools is a great resource for learning or refreshing your knowledge of any of these concepts.
HTML DOM (accessing HTML DOM using getElementById)
The HTML Document Object Model (DOM) represents the structure of your HTML document as a tree of objects. JavaScript can interact with this tree to dynamically change the content and behavior of your webpage.
Accessing HTML elements in JavaScript:
getElementById is a JavaScript method that allows you to access a specific HTML element by its id attribute. For example, if your HTML has elements with IDs like canvas, speedRange, and clear-button, you can access them in your JavaScript code like this:
Example
1
2
3
4
5
const canvasElement = document.getElementById('canvas');
const speedSliderElement = document.getElementById('speedRange');
const clearButtonElement = document.getElementById('clear-button');
console.log(canvasElement); // This will log the canvas HTML element to the console.
Further reading: w3schools HTML DOM
Event listeners
Event listeners allow you to respond to specific events that happen on your webpage, such as a user clicking a button or moving their mouse. We attach event listeners to HTML elements using JavaScript.
Here’s an example of how to add an event listener to a “Clear Screen” button:
Example
1
2
3
4
5
6
7
const clearButtonElement = document.getElementById('clear-button');
// The arrow syntax is called a lambda expression
clearButtonElement.addEventListener('click', () => {
// When the user clicks on the clearButtonElement, this code will run
console.log('Clear button clicked!');
});
More info on lambda expressions or (arrow functions).
In this code:
- We get the button element using its ID.
- We use the
addEventListenermethod to attach a function to the'click'event. - The function inside
addEventListenerwill be executed every time the button is clicked.
Further reading: w3schools Event Listener