I want to keep it simple on my simple html page. 1 button to cycle background colors, 1 button to cycle text colors.
I found some code here on stackoverflow that works, for the background:
<script>
var colors = ["red", "blue", "green"];
var colorIndex = 0;
function changeColor() {
var col = document.getElementById("body");
if( colorIndex >= colors.length ) {
colorIndex = 0;
}
col.style.backgroundColor = colors[colorIndex];
colorIndex++;
}
</script>
<body id='body'>
<button onclick="changeColor();">Change color</button>
</body>
and then I found some other code that was similar, that could be used along the other code, for the text color, but it doesn’t work:
<script>
function changeColor(){
var element = document.getElementById("questionContainer");
element.className = "myClass";
}
.myClass{
color:red;
}
</script>
<div id="questionContainer">
<p><strong><em> QUESTION: WHAT IS YOUR NAME?</em></strong></p>
</div>
<button onclick="changeColor()">COLORCHANGER<button>
I can’t get it to work. pulling my hair out.
I tried either code block by itself in a plain .html for testing. the one for background works, the one for text does not.
2
Answers
here's the code I have so far (a bit cleaned up)
'''
You have added the CSS class inside the
script
block.script
block is meant for javascript code only. I have edited your 2nd piece of code as follows