JavaScript Webpage Workout - M1 L1 Exercise 1
July 08, 2020
This exercise follows the warm-up for Lesson 1. Please do that warm-up first for this exercise to make more sense.
📺 This exercise also available as a video.
We’ll use the same steps we learned in the warm-up to CAMEL but now using buttons which are very common elements to interact with on a webpage.
Create
Let’s CREATE a button element in the HTML document and we’ll give it an id of red-btn using kabob-case. Then add the text content of ‘Red’ between the tags.
<!-- CREATE THE ELEMENT -->
<button id="red-btn">Red</button>Let’s add some CSS to the button.
button {
margin: 1.3rem;
width: 7.5rem;
height: 2.5rem;
padding: .5rem;
background-color: whitesmoke;
font-size: 1.3rem;
outline: none;
box-shadow: 0 0 3px darkgray;
curser: pointer;
}
button:active {
box-shadow: inset 0 0 3px darkblue;
}
#red-btn {
background-color: red;
color: white;
}Access
Next, let’s ACCESS the button in JavaScript with getElementById() and save it to a variable called redBtn using camelCase.
<!-- ACCESS THE LOCATION OF THE ELEMENT ON THE DOM -->
const redBtn = document.getElementById('red-btn');Let’s console.log() redBtn to make sure it’s what we think it is.
console.log(redBtn);"<button id='red-btn'>Red</button>"Manipulate
We can use the same makeRed function we used in the warm-up to MANIPULATE the text.
function makeRed() {
paragraph.style.color = 'red';
}But now we change the event listener to listen for a click on the button element and not the paragragh element. We’ll use the variable we made above redBtn.
Events and Listeners
redBtn.addEventListener('click', makeRed);Now when we click the button, it calls the function makeRed to turn the paragraph text to red.
Your Turn
Practice Exercise 1 with these two challenges.
- make a
buttonelement to turn the paragraph text to blue - make a
buttonelement to reset the paragraph text back to black.
There should be three buttons in total:
- one for turning the text red (we’ve already finished that),
- another button for turning it blue
- and a third for resetting the text back to black.
Keep the sequence in mind as you make these.
CREATE - ACCESS - MANIPULATE - EVENTS - LISTENERS
You can compare your work with mine here at CodePen or watch the video.
M1 L1 Exercise 1 Solution
Keeping practicing by moving to Exercise 2.
This blog post lesson in video format.
Keep practicing! Do the Your Turn challenge above then Go on to exercise 2.