Change color of a div using JS

2

I'm trying to make a div element change background color when selecting the color of my input using Js. I'm not getting anyone to help me?

<style>
    .corExemplo {
        width: 150px;
        height: 150px;
        border-radius: 50%;
        margin-bottom: 30px;
        float: left;
    }
</style>

<script>
    function trocaCor(){
        var cor = getElementById("corum").value;
        document.getElementById("boxum").style.backgroundColor = cor;
    }
</script>

<div id="boxum" class="corExemplo">Teste</div>

<form action="#" style="clear: both;">
    <label for="corum">Cor 1</label>
    <input type="color" id="corum" onchange="trocaCor();">
</form>

    
asked by anonymous 29.08.2016 / 23:55

2 answers

2

Only document. was prefixed getElementById("corum").value;

See below the working code:

function trocaCor(){
   var cor = document.getElementById("corum").value;
   document.getElementById("boxum").style.backgroundColor = cor;
}
    .corExemplo {
        width: 150px;
        height: 150px;
        border-radius: 50%;
        margin-bottom: 30px;
        float: left;
    }
<div id="boxum" class="corExemplo">Teste</div>

<form action="#" style="clear: both;">
    <label for="corum">Cor 1</label>
    <input type="color" id="corum" onchange="trocaCor();">
</form>
    
30.08.2016 / 00:00
1
  

The Allan's answer works perfectly. I'll just add an example with the addEventListener for knowledge purposes.

You can use Element.addEventListener() to "wait for an event" and perform the color change.

For your example I would consider something unnecessary, but since I said that you are starting in the world of JavaScript now, I think it would be very interesting to see.

Your example using this method would look like this:

var cor = document.getElementById("corum");

cor.addEventListener("change", function() {
    document.getElementById("boxum").style.backgroundColor = cor.value;
}, false);
.corExemplo {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  margin-bottom: 30px;
  float: left;
}
<div id="boxum" class="corExemplo">Teste</div>

<form action="#" style="clear: both;">
    <label for="corum">Cor 1</label>
    <input type="color" id="corum">
</form>

In this way, I add the event change() to input to addEventListener() , not directly to input .

    
30.08.2016 / 00:17