Search code examples
javascriptcsshoverpointer-events

How to change an image on mouseover of wrapper div


I am trying to set up a simple script where a linked image changes on hover, on an ESRI Map Journal template. Normally I would do something like this;

<script language="javascript">
    function MouseRollover(MyImage) {
    MyImage.src = "image2";
}
    function MouseOut(MyImage) {
    MyImage.src = "image1";
}
</script>

<a href="link">
<img src="image1" onMouseOver="MouseRollover(this)" onMouseOut="MouseOut(this)">
</a>

This does not work on Map Journal, however, because the template automatically inserts a wrapper div with a pointer-event: all; property. The reason why it does this, is because images are automatically set to open in lightbox by the Map Journal template. So to counteract that, and allow for the image to be linked to something else, the wrapper div is used. So it becomes;

<a href="link">
<div id="image-wrapper" style="pointer-events: all; display: inline-block; cursor: default; max-width: 100%; position: relative;">
<img src="image1" onMouseOver="MouseRollover(this)" onMouseOut="MouseOut(this)"></div>
</a>

In so doing, however, it deactivates the above hover script. If I override the div CSS with pointer-event: none, the hover script works but then the link doesn't function.

Any suggestions on resolving this, so that both the link and the hover will work? I thought about having changing the script so that mouseover is acting on the div, but then it changes the image. How can I code this in JS? Or maybe there is a different solution?


Solution

  • This works with no javascript, just css. Always better when possible. Let me know if this works for you.

     .default-image {
       display: block;
     }
     .hover-image {
       display: none;
     }
     #image-wrapper:hover .default-image {
       display: none;
     }
     #image-wrapper:hover .hover-image {
       display: block;
     }
    <a href="link">
      <div id="image-wrapper" style="pointer-events: all; display: inline-block; cursor: default; max-width: 100%; position: relative;">
        <img class="default-image" src="http://assets.pokemon.com/assets/cms2/img/pokedex/full//006.png" />
        <img class="hover-image" src="http://assets.pokemon.com/assets/cms2/img/pokedex/full//001.png" />
      </div>
    </a>