Change color of div in onclick event - JS

Asked

Viewed 141 times

0

This 'Generate Square' function creates a red-colored square-shaped div. What I’m trying to do is change the color of the squares when I click on it. (I don’t know how to pass the generated element as a parameter in the function, I need help in this as well.)

Document Square Generate

</div>

<script>
    function gerarQuadrado() {
        var boxElement = document.createElement('div');
        boxElement.style.height = '100px';
        boxElement.style.width = '100px';
        boxElement.style.backgroundColor = '#f00';
        boxElement.style.margin = '10px';
        boxElement.setAttribute('class', 'box');
        boxElement.setAttribute('onclick', 'mudarCor(self)');

        var divElement = document.querySelector('div#app');
        divElement.appendChild(boxElement);
    }

    function mudarCor(box) {
        var letters = "0123456789ABCDEF";
        var color = "#";
        for (var i = 0; i < 6; i++) {   
            color += letters[Math.floor(Math.random() * 16)];  
        }
        this.box.style.backgroundColor = color;
    }


</script>

2 answers

0


The self cannot be sent as a parameter to the function because it has nothing to do with the context. See the topic below:

What you have to send is the this, which will reference the element clicked on the function, which will be assigned to the variable box that you put:

boxElement.setAttribute('onclick', 'mudarCor(this)');

And in function, do not put the this before the object box, because the box is not a property of the object window, which is referenced by this in function:

box.style.backgroundColor = color;

Behold:

function gerarQuadrado() {
     var boxElement = document.createElement('div');
     boxElement.style.height = '100px';
     boxElement.style.width = '100px';
     boxElement.style.backgroundColor = '#f00';
     boxElement.style.margin = '10px';
     boxElement.setAttribute('class', 'box');
     boxElement.setAttribute('onclick', 'mudarCor(this)');

     var divElement = document.querySelector('div#app');
     divElement.appendChild(boxElement);
 }

 function mudarCor(box) {
     var letters = "0123456789ABCDEF";
     var color = "#";
     for (var i = 0; i < 6; i++) {   
         color += letters[Math.floor(Math.random() * 16)];  
     }
     box.style.backgroundColor = color;
 }
gerarQuadrado();
<div id="app"></div>

-1

Try instead of putting "self" in the boxElement method.setAttribute('onclick', 'mudarCor(self)');, put the "this" boxElement.setAttribute('onclick', 'mudarCor(this)');

Browser other questions tagged

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