Move image while hovering over it

Asked

Viewed 195 times

0

I’d like to help with a study I’m doing.

How can I move an image, randomly and dynamically, by passing the mouse on it? I would like a line of reasoning to come up with a solution in my future problems.

I took a course in Javascript and acquire much knowledge, however, when it is time to apply it, I stay stuck to the problem.

Could you guide me in this example?

  • Raul, it’s easier to get help if you put what you’ve done and where you’re standing, your question gets less broad and more people can guide you.

  • If the modification I made, do not agree. Please reverse it.

1 answer

0


//variável que verificará se o mouse está sobre a imagem
let hover = false;

//Função que moverá a imagem
function move(element) {
  //Muda as propriedades top e left da imagem
  element.style.top = `${Math.random() * (10 - (-10)) + (-10) + Number(element.style.top.replace('px', ''))}px`;
  element.style.left = `${Math.random() * (10 - (-10)) + (-10) + Number(element.style.left.replace('px', ''))}px`;
  
  //Math.random() * (10 - (-10)) + (-10)
  //Número aleatório entre -10 e 10
  
  //Number(element.style.top/left.replace('px', ''))
  //A posição atual da propriedade top/left como um número

  //Se o mouse ainda está sobre a imagem
  if (hover) {
    //Chama a função move novamente em meio segundo
    setTimeout(() => move(element), 500);
  }
}

//O elemento imagem
const image = document.querySelector('img');

//Quando o mouse ficar sobre a imagem
image.addEventListener('mouseover', function(event) {
  //Altera a variável hover
  hover = true;

  //Move a imagem
  move(image);
});

//Quando o mouse sair da imagem
image.addEventListener('mouseout', function(event) {
  //Altera a variável hover
  hover = false;
});
img {
  position: absolute;
  top: 0px;
  left: 0px;
  transition: top 0.5s linear, left 0.5s linear; 
}
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTdmLKDoD_jt79twxzn55JzrJDaHpkpl8bvarPloOFOsy4eLDA3" alt="Exemplo">

  • Thank you, I managed to understand the logic, helped me a lot friend

Browser other questions tagged

You are not signed in. Login or sign up in order to post.