0

I am trying to run a CSS animation only when the mouse hovers over a certain element. Basically, if a mouse hovers over the parent element container, I want the child element light to run its animation only when it is hovered over. I would like to achieve this with JavaScript/jQuery since I am unsure if this is possible with just CSS alone. I am also new to JavaScript!

.light {
  position: absolute;
  transform: translate(-200%, 20%);
  width: 4px;
  height: 4px;
  border-radius: 5px;
  background: #0f0;
  filter: hue-rotate(80deg);
  z-index: 2;
  animation: light 1s linear infinite;
}

@keyframes light {
  *some animation*
}
<div class="container">
  <div class="light"></div>
</div>

I am sorry if this is a basic question, but I've research for hours with no success!

isherwood
  • 58,414
  • 16
  • 114
  • 157
Amari
  • 71
  • 5
  • That's not a good reason to default to scripting. You absolutely _can_ apply animations on ancestor hover with CSS. – isherwood May 06 '21 at 21:25
  • I am sorry. I was just unsure if CSS would work, and it seemed like Javascript would be more efficient. I would gladly accept a CSS solution as well if that is more efficient – Amari May 06 '21 at 21:31
  • You have one below and many above. If you actually want to do it with JS, that's been covered well before also. – isherwood May 06 '21 at 21:31

2 Answers2

1

Use :hover?

.light {
  width: 40px;
  height: 40px;
  border-radius: 5px;
  background: green;
}

.container {
  border: 1px dotted red;
}

.container:hover > .light {
  animation: light 1s linear infinite;
}

@keyframes light {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
<div class="container">
  <div class="light"></div>
</div>
Will
  • 3,201
  • 1
  • 19
  • 17
0

If you are looking to do this with JavaScript, you could add a hover class on mouseover and add the keyframes animation to your .light.hover in your css like this:

var target = document.querySelector(".light");
target.addEventListener("mouseover", mouseOver, false);
target.addEventListener("mouseout", mouseOut, false);

function mouseOver() {
   target.classList.add("hover")
}

function mouseOut() {  
    target.classList.remove("hover")
}
.light {
  width: 100px;
  height: 100px;
  border-radius: 5px;
  background: #0f0;
}

.light.hover {
  animation: light 3s linear infinite;
}

@keyframes light {
  from {
    filter: hue-rotate(0);
  }

  to {
    filter: hue-rotate(180deg);
  }
}
<div class="light"></div>

But the CSS way is just to use:

.light {
  width: 100px;
  height: 100px;
  border-radius: 5px;
  background: #0f0;
}

.light:hover {
  animation: light 3s linear infinite;
}
Ali Klein
  • 1,811
  • 13
  • 13