10.4: DOM Manipulation
Learning Objectives:
By the end of this lesson, you should be able to:
Introduction
We have seen how we can manipulate the DOM via JavaScript in the console. Now let's take a look at how we can pre-program DOM manipulation to happen based on user input.
Conceptually, we are still just defining inputs and outputs. Now inputs include how the user interacts with the browser, which can include mouseovers, scrolls, drag and drops, clicks or double clicks, and output is manipulation of the Document that the user is interacting with.
Inputs and Outputs
Defining an Input
An input to our JavaScript program is called an event. Similar to how we can define functions as blocks of code that will only run when the function is called, we can write code that will only run when the user interacts with the browser via an event. We do this with the provided .addEventListener(
) method. The method takes in 2 inputs:
The event type
The code block to be executed when the event is triggered, defined as a function.
Some useful events include:
click
dblclick
keypress
keydown
keyup
You can find a more complete list with explanations of each event on this page.
Let's go back to basics, and print out "Hello, world!" in the console whenever a button is clicked. The syntax for that might look something like this:
This means we can program the browser in such a way that when the user makes an action, the browser calls our function - and this is exactly how our main
function works. Except that we aren't just limited to clicking on the submit button or getting the value the user typed into an input field/textbox.
The function for an event is referred to as a callback function. In the case of an event listener, the callback function takes the triggered event as an input parameter and does whatever actions it was declared to do due to this trigger. Now we can look at how this was defined for you in index.html of the starter code:
Advanced Applications in the Browser
The pattern of:
Being able to create any representation of data on the screen
Have complete control over what actions the user can take at any time
means that your app should have complete control over every element on the screen.
Modern development for applications that run in the browser ( the browser is the front-end ) are libraries and frameworks that allow programmers to manage all of these elements and inputs.
Some popular libraries include ReactJS, Angular, and Vue. These are well out of the scope of SWE Fundamentals; React is one of the later modules in Rocket's Bootcamp.
More Examples
Read through the comments to see what's actually happening.
Exercises
Follow Along
Implement the above code.
Using fundamentals-starter-code, write logic that grabs and references HTML elements, and change the background color of the
container
element every time the submit button is clicked.
Last updated