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 trial
Italo Oliveira
4,289 PointsDOM styles aren't being shown
Greetings, guys! So I've created a html script with a <canvas> tag with id="game-display" In css I set a yellow border to this canvas
The yellow border works.
So I wanted to create a function in js to change the color of this border each second. In the script (the script tag in html file is just before the closing body tag </body>) I've set:
<script> var canvas = document.getElementById('game-display'); var border = canvas.style.border;
setInterval(changeColor, 1000);
function changeColor() {
if(border == "1px solid yellow") {
border = "1px solid red";
} else {
border = "1px solid yellow";
}
}
</script>
It doesn't work ): I've set some console.log in the function and the function is working and it always go to the else path. But the most strange thing is that when I type canvas.style in the console, it shows the list of css properties of the element but no one is defined, but actually there are some defined properties ):
Could you help me please?
1 Answer
Steven Parker
243,199 PointsThe "border" variable only stores the contents of the border style property as it was at the moment of the assignment. The variable itself is just a string and re-assigning it doesn't affect the state of the element.
To do that you'll need to reference "canvas.style.border" again in the function.
Italo Oliveira
4,289 PointsItalo Oliveira
4,289 PointsIt worked :P Thanks for this :D
But one more question, when I type canvas.style.border on the console it shows an empty string, why this?
Steven Parker
243,199 PointsSteven Parker
243,199 PointsI would expect it to be empty until the first interval causes the function to set it.
If you're using a workspace, you could make a snapshot of your workspace and post the link to it here to facilitate detailed analysis.