javascriptmouseovermouseout

Mouseover & Mouseout w/ Javascript


I'm trying to call functions for mouseover and mouseout. I've tried a variety of different solutions that I've found here with no luck.

Here's where I'm at. Please explain the solution as I'm interested in understanding the issue and not just looking for a quick fix.

function MouseOver(elem) {
document.getElementsByName(elem).style.color("white");
}

function MouseOut(elem) {
document.getElementsByName(elem).style.color("black");
}

<nav id="frame-link">
<a href="index.html" name="home" onmouseover="MouseOver(this);" onmouseout="MouseOut(this);">Home</a>
</nav>

Solution

  • When you call an inline event handler such as you do with onmouseover="MouseOver(this);" you're passing a reference to the element itself to your function, and in your function you're taking that reference and assigning it to the variable elem.

    You would then normally use elem within your function like elem.style.color = "white";, not with parenthesis, as you're not running a function but rather just changing a property.

    function MouseOver(elem) {
      elem.style.color = "white";
    }
    
    function MouseOut(elem) {
      elem.style.color = "black";
    }
    <nav id="frame-link">
      <a href="index.html" name="home" onmouseover="MouseOver(this);" onmouseout="MouseOut(this);">Home</a>
    </nav>