Pass url to hovered / focused image

Viewed 43

I have some html / css code that is able to display an image on hover over some text and on click, that image will become focused and remain on the page:

CSS portion
.hover_img a { position:relative; }
.hover_img a span { position:absolute; display:none }
.hover_img a:hover span {display:block; overflow:visible; height:200px; width:200px;position:absolute}
.hover_img a:focus span {display:block; overflow:visible; height:200px; width:200px}
HTML portion
<div class="hover_img">
<a href="#">German Shepherd
<span>
<img src="https://s3.amazonaws.com/cdn-origin-etr.akc.org/wp-content/uploads/2017/11/12213218/German-Shepherd-on-White-00.jpg" alt="German Shepherd" />
</span>
</a>
</div>

The above code words well. The problem is that when I hover and/or focus on the text 'German Shepherd", I want that hovered/focused image to be clickable and, when clicked on, would take the user to a new page. In other words, I would want something along the lines of:

HTML portion
<div class="hover_img">
<a href="https://www.akc.org/dog-breeds/german-shepherd-dog/">German Shepherd
<span>
<img src="https://s3.amazonaws.com/cdn-origin-etr.akc.org/wp-content/uploads/2017/11/12213218/German-Shepherd-on-White-00.jpg" alt="German Shepherd" />
</span>
</a>
</div>

However, if the above is implemented, then clicking the word 'German Shepherd' automatically takes the user to the URL. However, on the page where the hovered / focused image is displayed, they can click on that image and go to the correct website as well. I am trying to remove the former so that clicking on 'German Shepherd" only acts as a focus, and then the user clicks on the hovered/focused image to go to the URL.

html, javascript, or css would be fine, unless jquery makes it much easier.

1 Answers

Assuming there is a container element with the id of container:

  1. Add an event listener on the container element
  2. Any click event is listened for within the container
  3. Check if the <a> that was clicked has the pseudo class :hover
  4. If the not being hovered, prevent the click from happening, otherwise process the click normally.

This should work for you. Please let me know if I missed something:

document.getElementById('container').addEventListener('click', checkHover);

function checkHover(e) {
  if(!e.target.closest('a:hover') || e.target.nodeName == 'A') {
     e.preventDefault();
  }
}
Related