Search code examples
javascriptjqueryhideshowmouseenter

jquery "show" effect shows wrong element


I'm trying to get two icons, "Up" and "Down", to turn a darker color when I hover over them. So I made two more icons, "UpHover" and "DownHover", which start out hidden, and are respectively shown when I mouseenter Up or Down, and hidden again when I mouseleave them. Down works normally, but for some reason, when I mouseenter Up, both Up and Down are hidden, and both UpHover and DownHover are shown.

When I erase the line $(".UpHover").show(); (I put asterisks around it below) the effect stops, so the error must be in that line. But I can't for the life of me figure out why that line would have anything to do with Down or DownHover. What am I missing?

<%= link_to image_tag("Up.png", class: "Up"), '#' %>
<%= link_to image_tag("Down.png", class: "Down"), '#' %>
<%= link_to image_tag("UpHover.png", class: "UpHover"), '#' %>
<%= link_to image_tag("DownHover.png", class: "DownHover"), '#' %>
<script type="text/javascript">
  $(".UpHover").hide();
  $(".DownHover").hide();
  $(".Up").mouseenter(function () {
    $(".Up").hide();
    ***$(".UpHover").show();***
  });
  $(".UpHover").mouseleave(function () {
    $(".Up").show();
    $(".UpHover").hide();
  });
  $(".Down").mouseenter(function () {
    $(".Down").hide();
    $(".DownHover").show();
  });
  $(".DownHover").mouseleave(function () {
    $(".Down").show();
    $(".DownHover").hide();
  });
</script>

Solution

  • Change the order of the images so that the replacement is next to the image it replaces.

    <%= link_to image_tag("Up.png", class: "Up"), '#' %>
    <%= link_to image_tag("UpHover.png", class: "UpHover"), '#' %>
    <%= link_to image_tag("Down.png", class: "Down"), '#' %>
    <%= link_to image_tag("DownHover.png", class: "DownHover"), '#' %>
    

    What's happening is that when you hide Up, the Down image move up to fill in that space. Since that's where the mouse is, the $(".Down").mouseenter event fires, and it gets hidden as well.

    When you reorder it, UpHover fills in the Up place.