Search code examples
javascriptjqueryhtmlmouseoveronmouseover

onmouseover function triggering without having moused over the element


What I want to accomplish is this: when you mouseover the "albatross" id image, the "skua" id image fades out. As the code currently is, the skua image fades out as soon as the page loads, no matter where the mouse is on (or off) the page.
Both the albatross and skua images are positioned absolutely in a separate stylesheet.

document.getElementById("#albatross").onmouseover = fadeRest();
function fadeRest() {
  $("#skua").fadeOut();
}


Something else I tried was this:
document.getElementById("albatross").addEventListener("mouseover", fadeRest()); with the same fadeRest function, which behaves the same way as the code above. However, if I add a # to albatross, the skua image will no longer fade, no matter whether I mouse over the albatross or not.
I changed the fadeRest function to an alert to see whether the mouseover was being registered at all, and got no alert so it seems as though the event listener is not being added.

Anything that helps me understand what I'm doing wrong would be greatly appreciated, thanks.


Solution

  • Since you're using jQuery, you can do it this way

    $('#albatross').hover(function() {
      $("#skua").fadeOut();
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="albatross">albatross</div>
    <div id="skua">skua</div>

    If you wanted to have a mouseleave event...

    $('#albatross').hover(function() {
      $("#skua").fadeOut();
    }, function() {
      $("#skua").fadeIn();
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="albatross">albatross</div>
    <div id="skua">skua</div>

    You can also use $.on() with the event name

    $('#albatross').on('mouseenter', function() {
      $("#skua").fadeOut();
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="albatross">albatross</div>
    <div id="skua">skua</div>