How to execute a given function using onmouseover?

Asked

Viewed 88 times

0

I’m trying to do an exercise, in which I need to do the following process:

Using the result of the first challenge, every time the user passes the mouse over some square changes its color to a random color generated by the function below:

function getRandomColor() {
 var letters = "0123456789ABCDEF";
 var color = "#";
 for (var i = 0; i < 6; i++) {
 color += letters[Math.floor(Math.random() * 16)];
 }
 return color;
}
var newColor = getRandomColor();

The solution I found for the first challenge quoted was the following:

var btn = document.querySelector('#criarQuad');
var container = document.querySelector('#app');

btn.onclick = function() {
       var quad = document.createElement('div');
       quad.style.width = '100px';
       quad.style.height = '100px';
       quad.style.backgroundColor = '#F00';

       return container.appendChild(quad);
       console.log(quad);
}

In the above function, every time the user clicks on the indicated button, a new square will be added. So I tried the following solution for the exercise cited at the beginning of the publication:

container.addEventListener('mouseover', function(e) {
          e.target.className == 'quadrado' ? e.target.setAttribute('style', 'background-color: ' + newColor) : undefined;
});

However, instead of changing the color of the square as you ask for the exercise, it erases the square that I pass the mouse and all that come in sequence, someone would know to tell me why this happens and how I could solve?

3 answers

3


Hello, the problem here is that when using the function setAttribute to change the value of the squares background color you remove all the contents of the property style, this includes the parameterization of width and height, its square is not being removed, it is assuming the proportions 0x0 px.

To resolve this change the code snippet

e.target.setAttribute('style', 'background-color: ' + newColor)

for

e.target.style.backgroundColor = newColor

You can even put this notation as a conventional if, and I advise you to place your color generation function call within your Eventlistener

container.addEventListener('mouseover', function(e) {
   if (e.target.className == 'quadrado') {
      e.target.style.backgroundColor = getRandomColor();;
   }
});

Another important detail, I’m assuming that you correctly added the "square" class name to your squares, otherwise they wouldn’t disappear as you mentioned, but if you didn’t, include the lower portion within your onclick function

quad.classList.add("quadrado");
  • thank you very much, I did not care that the solution was in my face all the time rs, it worked perfectly!

1

Hello, I know it’s been answered but I want to leave my contribution here.

I also came across this exercise and decided to create an attribute onmouseover for every square added. Then I used the function to create random colors - getRandomColor() - and finally used the function - changeColor() - to change the color.

Thus:

    function addBox(){
      let div = document.createElement('div')

      div.style.width = '100px'
      div.style.height = '100px'
      div.style.borderRadius = '15px'
      div.style.background = 'red'

      div.setAttribute('onmouseover','changeColor(this)')

      body.appendChild(div)
    }

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

    function changeColor(div){
      div.style.width = '100px'
      div.style.height = '100px'
      div.style.borderRadius = '15px'
      div.style.background = getRandomColor()
    }

//Ready!!

-1

        var buttonElement = document.querySelector('button#botao');
        buttonElement.onclick = function(){
            let boxElement = document.createElement('p');
            boxElement.style.backgroundColor = 'red';
            boxElement.style.width = '100px';
            boxElement.style.height = '100px';
            let containerElement = document.querySelector('div');
            containerElement.appendChild(boxElement);
            containerElement.onmouseover = function(){
                boxElement.style.backgroundColor = getRandomcolor();
            }
        } 

            function getRandomcolor(){
            var letters = "0123456789ABCDEF";
            var color = "#";
            for (var i = 0; i < 6; i++){
                color += letters[Math.floor(Math.random() * 16)];
            }   
            return color;
        }
                  
    </script>

Browser other questions tagged

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