skip to Main Content

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


  1. Chosen as BEST ANSWER

    here's the code I have so far (a bit cleaned up)

    <html><head><style>
    
    .myClass{
    color:red; 
     }
    
    </style></head>
    <body id='body'>
    
    <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++; 
        var element = document.getElementById("testText");
        element.className = "myClass";
        }
    </script>
    
    <button onclick="changeColor();">change background color</button>
    
    <div id="testText"> 
    <p><strong><em>TEST TEXT</em></strong></p>
    </div>
    <button onclick="changeColor()">change text color</button>
    
    </body>
    </html>
    

    '''


  2. 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

    <script>
        function changeColor(){
            var element = document.getElementById("questionContainer");
            element.className = "myClass";
        }
    </script>
    <style>
    .myClass{
       color:red; 
    }
    </style>
    
    <div id="questionContainer"> 
    <p><strong><em> QUESTION: WHAT IS YOUR NAME? 
    </em></strong></p>
    </div>
    <button onclick="changeColor()">COLORCHANGER<button>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search