I'm creating a website via the Code.org Web Lab, and I've got a variable within tags that I'd like to recolour once it hits 100. What code should I use, within HTML or Javascript parts of the page, to achieve this?
This is a new concept to me, adding Javascript to HTML, so I looked it up on Google and Stack Overflow for answers. Every result just talked about either colouring certain words in a paragraph, or saving colours in javascript variables.
Here's the Javascript within the page that contains the variable in question:
<script>
function clickCounter() {
if (typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount)+1;
} else {
localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "People have attempted but failed to help me " + localStorage.clickcount + " times.";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support helping me.";
}
}
</script>
And here's the HTML associated with the clicking variable:
<p><button onclick="clickCounter()" type="button"><b>HELP ME</b></button></p>
<div id="result"></div>
The code itself works perfectly, but I don't have any idea how to colour it once it gets to 100 clicks. If anyone could help me, it would be appreciated.
Considering that you did not add the element you want the color to be changed, I'm going to add a <p>
here.
You can change text color of an element with .style.color
.
Most CSS styles can be modified with HTMLElement.style
.
A style applies to 1 HTML element and everything within that particular element as well so, if you apply the color to <div id="result"></div>
, the whole thing will have its color changed.
To fix that, you have to change the HTML so that you can target the specific part you want to change. Here, I wrapped localStorage.clickcount
with <span id="recolor"></span>
.
Then, you can target recolor
and change its color when localStorage.clickcount >= 100
.
<script>
function clickCounter() {
if (typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount)+1;
} else {
localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "People have attempted but failed to help me <span id='recolor'>" + localStorage.clickcount + "</span> times.";
if (localStorage.clickcount >= 100) {
document.getElementById("recolor").style.color = "blue";
}
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support helping me.";
}
}
</script>
<p><button onclick="clickCounter()" type="button"><b>HELP ME</b></button></p>
<div id="result"></div>