Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 481
Tommy.Collins Avatar asked Aug 18 '26 05:08

Tommy.Collins


2 Answers

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>
like image 140
j08691 Avatar answered Aug 20 '26 19:08

j08691


If it's truly just styling that needs to change, then you don't need JavaScript at all. You can just use CSS with the :hover pseudo-class:

.normal { background-color:#e0e0e0; }
.normal:hover { background-color:yellow; }
<nav id="frame-link">
<a href="index.html" name="home" class="normal">Home</a>
</nav>

But, if it's more than just styling, then you'll want to do this the modern, standards-based way. Don't use inline HTML event handling attributes (see here for why). This syntax is a little more typing, but well worth it for all the benefits it brings.

Lastly, (and again), if it is styles that you're after, working with classes is much simpler than working with individual style properties.

// Get a reference to the element that needs to be worked with
var theLink = document.querySelector("a[name='home']");

// "Wire" the element's events
theLink.addEventListener("mouseover", mouseOver);
theLink.addEventListener("mouseout", mouseOut);

function mouseOver() {
  theLink.classList.add("hovered");
}

function mouseOut() {
  theLink.classList.remove("hovered");
}
.normal { background-color: #e0e0e0; }
.hovered { background-color: yellow; }
<nav id="frame-link">
  <a href="index.html" name="home" class="normal">Home</a>
</nav>
like image 33
Scott Marcus Avatar answered Aug 20 '26 19:08

Scott Marcus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!