Jump to content

Show image on hover text (follow mouse) not working correctly. Pls help

Recommended Posts

Hey, 

I just cant figure out what the problem is. I am trying to show an image after I hover a text. The image should follow the mouse and should be centered. Z-Index isnt working or its not showing up when its value is -1. 

Here are all the codes. Would be great if someone could help. Thanks a lot!

Site: https://swan-frog-cepd.squarespace.com/

Pass: bnn2022

 

CSS:

#container {
  position: relative;
}
.followMouse {
  z-index: 0;
  position: absolute;
}

 

HTML:

<div id="container">
  <a href="" data-src="https://static1.squarespace.com/static/5f6c5e26dc4b6338ce9bcba6/t/622f06150ab78218bb811425/1647248921305/German_Facts_02.png" class="hover">
    <h1>New</h1>
  </a>
</div>

 

JavaScript:

<script>
for (let el of document.querySelectorAll('.hover')) {
  let image = new Image();
  image.src = el.dataset.src;
  image.className = "followMouse";
  el.addEventListener('mouseover',(e)=>{
    document.getElementById('container').append(image);
    image.style.left = `${e.x - (image.width/1)}px`;
    image.style.top = `${e.y - (image.height/1)}px`;
  })
  el.addEventListener('mouseout',(e)=>{
    image.remove();
  })
}
window.addEventListener('mousemove',(e)=> {
  let image = document.querySelector('.followMouse');
  if (image) {
    image.style.left = `${e.x - (image.width/1)}px`;
    image.style.top = `${e.y - (image.height/1)}px`;
  }
})
</script>

 

 

Link to comment
  • Replies 1
  • Created
  • Last Reply

Top Posters In This Topic

Top Posters In This Topic

Create an account or sign in to comment

You need to be a member in order to leave a comment

×
×
  • Create New...

Squarespace Webinars

Free online sessions where you’ll learn the basics and refine your Squarespace skills.

Hire a Designer

Stand out online with the help of an experienced designer or developer.