Training with Javascript - colors

Asked

Viewed 46 times

0

What problem in my code? I believe the logic is correct!

<h1 id="colorchange">ESTAMOS FAZENDO TESTE DE CORES COM JAVASCRIPT!</h1>
<input type="text" name="Cor" id="whatcolor"><br /><br>
<button type="button" onclick="newcolor('whatcolor')">Mudar</button>
<script>
        function newcolor(thecolor) {
        document.getElementById('colorchange').style.color = thecolor;
    }
</script>
  • 1

    You are apparently defining the color of colorchange as being 'whatcolor' and that’s not a valid color. What you tried to do and what you expected to happen?

1 answer

1

I believe you’re trying to do something like this:

<h1 id="colorchange">ESTAMOS FAZENDO TESTE DE CORES COM JAVASCRIPT!</h1>
<input type="text" name="Cor" id="whatcolor"><br /><br>
<button type="button" onclick="newcolor('whatcolor')">Mudar</button>
<script>
  //A função recebe o id do elemento input e pega o seu valor
  function newcolor(id) {
    document.getElementById('colorchange').style.color = document.getElementById(id).value;
  }
</script>

Or pick up directly, without receiving the element id input

<h1 id="colorchange">ESTAMOS FAZENDO TESTE DE CORES COM JAVASCRIPT!</h1>
<input type="text" name="Cor" id="whatcolor"><br /><br>
<button type="button" onclick="newcolor()">Mudar</button>
<script>
  function newcolor() {
    document.getElementById('colorchange').style.color = document.getElementById('whatcolor').value;
  }
</script>

  • That’s exactly what I wanted, I understood your code. Just a question, , why did you have to pick up for Document? Since the ID was already in Function.. And another point, when you call the color it reads in string or Int? Thanks for your help man, I’m learning a lot! :))

  • I don’t understand, if I don’t call for document I will call where? The id that is received is the string, not the element. The value of document.getElementById(id).value it will always be a string, because there is no color only numeric, if you want red, for example, you can use "#900", but there is a "#" in the front, as well as rgb, rgba, hsl, etc (which will have parentheses and comma)

  • Hi Costa, I understand the logic, thank you for your support! ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.