Home > front end >  How can i run mouseenter function more times?
How can i run mouseenter function more times?

Time:04-04

How can i run mouseenter function more times? The problem is that I want theobject to rotate every time mouseenters, but it only works once and than nothing. I want it to gain 80deg on every hover, however right now it only gets on position of 80deg and it can't continue, how can I make it work like on every mouseenter add 80deg?

JS

const astrx = document.querySelector(".hero__asterix");

astrx.addEventListener('mouseenter', () => {
  astrx.style.transform= "rotate(80deg)"
})

HTML

<img src="./assets/Lime-asterix.svg" alt="Lime Asterix Dövr" >

SASS

&__asterix
        position: relative
        top: 10.3rem
        left: 62%
        transition: 1.5s ease-in-out

CodePudding user response:

This happens because rotate(80deg) rotates an object relative to the original position (that is 0 deg), not relative to the previous one

You do probably want to save degrees and increase them each time:

dg = 80;

astrx.addEventListener('mouseenter', () => {
  astrx.style.transform= `rotate(${dg}deg)`;
  dg  = 80;
})

CodePudding user response:

The mouseenter event does run more than once, the problem is that the style has already been applied to the element after the first run so there is no style change on subsequent runs.

You can keep track of the total rotation in a variable (angle) then increase angle by 80 and update the style on the element using angle.

Here's an example:

const asterix = document.querySelector(".asterix");

let angle = 0;

asterix.addEventListener("mouseenter", () => {
  angle  = 80;
  asterix.style.transform = `rotate(${angle}deg)`;
});
.asterix {
  background-color: blue;
  width: 100px;
  height: 100px;
}
<div >

  • Related