Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialTibor Ruzinyi
17,968 PointsOne solution to change color after a second click :)
<!DOCTYPE html>
<html>
<head>
<title>JavaScript and the DOM</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h1 id="myHeading">JavaScript and the DOM</h1>
<p>Making a web page interactive</p>
<button id="mybutton">Click ME</button>
<script src="app.js"></script>
</body>
</html>
let x = 0;
let y = 2;
let g = 0;
const myHeading = document.getElementById('myHeading');
myHeading.addEventListener('click', () => {
x += 1;
let z = x % y;
console.log('z before if is : ' + z);
if( z == 0 ){
console.log('z after if is : ' + z);
myHeading.style.color = 'red';
console.log("x = "+x + " y = " + y + " z = " + z );
} else {
myHeading.style.color = 'purple';
console.log("x = "+x + " y = " + y + " z = " + z );
}
});
1 Answer
Mark Tripney
8,666 PointsIngenious! But, there's a more 'native' way to do this, using JS's toggle
method.
If we add a .turn-red
class to our CSS, like so (note, the class name is arbitrary)...
.turn-red {
color: red;
}
... we can simply add and remove this class from our target with the following:
const myHeading = document.querySelector("#myHeading");
myHeading.addEventListener("click", () =>
myHeading.classList.toggle("turn-red")
);
More information here (links to MDN).