Affecting the page
All our programs so far have just printed their results out to the console, but Javascript on real websites needs to do more than that.
Javascript is often used to show or hide parts of a page based on user actions. We often do this by adding and removing classes.
Let's say we have some HTML on our page:
<h1>My text here</h1>
And in our CSS, we have a class defined like this:
.red-text{
color: red;
}
We can use javascript to apply the red-text
class to our HTML based on how the user interacts with the page.
Selecting page elements
We can select HTML elements on our webpage and save them as variables like this:
const heading = document.querySelector("h1")
We can write any ID, class or element name inside document.querySelector("")
, just like in CSS.
You may see this referred to as selecting DOM elements.
Adding and removing classes
Once we've selected the right HTML and saved it as a variable, we can add a class to it like this:
const heading = document.querySelector("h1")
heading.classList.add('red-text')
When this code runs, the text should turn red.
We could also remove a class that already exists with:
heading.classList.remove('red-text')
Next, we'll look at how to trigger these changes based on things the user does.
Part of Adding interactivity
- Introducing Javascript
- Your first Javascript program
- Variables
- Conditional logic
- Affecting the page
- Making a menu
- Responding to user actions
- Keep your Javascript accessible
- Get confident with Javascript
- Add interactivity to your prototypesP