Determine if mouse is over an element

i know i can attach a mouseover event, but here’s a scenario…

let’s say i have an element that when i type the ‘R’ key it will change the color of the element, but only when the mouse is over that element. what’s the best/cleanest way to handle this?

if (/*the R key is pressed*/) {
     if (/*the mouse is over the element*/) {
          /*change the color*/
     }
}

actually, i think i just answered my own question - but i’m open to any alternatives. here’s what i did…

var mouse = false;
function mouseStatus(n) {
     mouse = n;
}
function changeColor() {
     if (/* the R key is pressed */) {
          if (mouse) {
               // change the color
          }
     }
}
<div onmouseover="mouseStatus(true);" onmouseout="mouseStatus(false);"></div>

works just like i want, at least.

Well rather then use global variables use the ability to add properties to objects on the fly. i.e. when the mouse is over the object set a new property called say mouseIsOver = true.


window.onload = initDivMouseOver;
function initDivMouseOver()   {
   var div = document.getElementById("mydiv");
   div.mouseIsOver = false;
   div.onmouseover = function()   {
      this.mouseIsOver = true;
   };
   div.onmouseout = function()   {
      this.mouseIsOver = false;
   }
   div.onclick = function()   {
      if (this.mouseIsOver)   {
         ....
      }
   }
}

<div id="mydiv"></div>

that’s definitely a good way to handle it, too. i usually create stuff like that on the fly. i don’t know why i didn’t think of that for this application. thanks!