Search code examples
javascriptvariablescolor-picker

Assigning a color picker color to a variable and using the variable for fontcolor using JavaScript


I am trying to assign a color from a color picker to a variable then use the variable value to change the color of the font. The variable value is getting assigned properly, but the code will not use the variable value to color the font. If I use a hard coded color the font color changes. Want to stick with just HTML and JS. Not wanting to use jQuery or CSS at this point. Any help would be greatly appreciated. Thanks in advance.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <script src="color_text.js" defer></script>

  </head>

    <body>

        <h2>Text Color Picker</h2>
        <form id="form3">
            Pick the color you want the text responses to be:
            <input type="color" id="favcolor" name="favcolor">
        </form>
        <button  id="myButton3" type="submit" name="submit" value="Submit">Submit</button>
        
        <p id="par3"></p>

    </body>
</html>

//Checking the input button3 for a click
document.getElementById("myButton3").addEventListener("click", () => {

    
    var x = document.getElementById("myButton3").value;
    
    //Check if register button
    if (x.includes("Submit")) {

      //assign value to favColor    
      var favColor = document.getElementById("favcolor").value;
        
    }
    
    var message3 = `the color you selected is: ${favColor}<br>`;
    
    document.getElementById("par3").innerHTML = message3.fontcolor("&(favColor)");  
 });

Solution

  • fontcolor() is a long-deprecated function. Even allowing for that, feeding it "&(favColor)" is invented syntax.

    If you wish to set the selected colour as the font colour of the #par3, you need:

    document.getElementById("par3").style.color = favColor;
    

    If you're just trying to populate #par3 with your message, you just need:

    document.getElementById("par3").innerHTML = message3;