Moe Tassi
Moe Tassi

Reputation: 15

Trouble with refering to a variable in mouseover event

I want to make an event where .gridss change colors with mouseover event. Problem is gridss comes out as not definied,and if i try to move the mouseover event into the the gridss function it also does not work. So how can I successfully refer to .gridds?

My question is pretty simple yet i cant seem to get it right,so thanks in advance.

const container = document.querySelector('#container');

$(document).ready(function() {
    for(var x = 0; x < 16; x++) {
        for(var y = 0; y < 16; y++) {
            let gridss = $("<div class='gridss'></div>");
            gridss.appendTo('#container');
        }
    }
});

gridss.addEventListener("mouseover", function( event ){
  event.target.style.color = "purple";

  setTimeout(function(){
    event.target.style.color = "";
  }, 10);
}, false);

Upvotes: 1

Views: 27

Answers (1)

zer00ne
zer00ne

Reputation: 43910

Use jQuery for events if you are using jQuery. I assume that you are not aware of mouseout or mouseleave because it looks like you are using setTimeout() to trigger a delay of text color reverting back to original color. I used mouseenter and mouseleave which are similar to mouseover and mouseout events.

You had an error which that gridss wasn't defined. The reason why moving in and out of functions didn't work is because you defined gridss with let.

  • let is limited scope to that of the block

  • var scope is the function which works as long as you have gridss in the function.

Demo

const container = document.querySelector('#container');

$(document).ready(function() {
  for (let y = 0; y < 32; y++) {
    var gridss = $("<div class='gridss'>TEST</div>");
    gridss.appendTo('#container');
  }
  $('.gridss').on('mouseenter mouseleave', function(e) {
    if (e.type === 'mouseenter') {
      this.style.color = "purple";
    } else {
      this.style.color = "white";
    }
  });
});
#container {
  border: 5px solid blue
}

.gridss {
  border: 3px solid red;
  height: 20px;
  margin: 10px 5px;
  text-align: center;
  background: cyan;
  font-weight: 900;
  color: white;
  transition: color .5s ease
}
<div id='container'></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Related Questions