Andre
Andre

Reputation: 5

Scale a button when user hovers over it

The Codepen linked below is where I currently am stuck.

function startHover(e) {
  btn.classList.add("btnPlaying")
}

function removeHover(e) {
  btn.classList.remove("btnPlaying");
}

const btn = document.querySelector('.btn')
btn.addEventListener("mouseenter", startHover);
btn.addEventListener('transitionend', removeHover);
.btn {
  margin-top: 10rem;
  padding: 20px 100px;
  background-color: rgb(255, 204, 3);
  border-radius: 10px;
  border-style: none;
  box-shadow: 0px 0px 10px black;
  color: blue;
  border: 4px solid rgb(53, 106, 188);
  transition: all 1.07s ease;
}

.btnPlaying {
  transform: scale(1.1);
}
<button class="btn">Play!</button>

https://codepen.io/TerrellsCode/pen/zYEyORB

The button grows and shrinks like intended but only does it one time. Look for any pointers on how to make this grow/shrink animation loop infinitely as long as user is hovering over button. Thank You

Upvotes: 0

Views: 64

Answers (2)

Emiel Zuurbier
Emiel Zuurbier

Reputation: 20954

No need for JavaScript. With CSS Keyframes you can create and run animations. Toggle the animation-play-state with the :hover selector to start and pause the animation.

@keyframes grow-shrink {
  from {
    transform: scale(1);
  }
  
  to {
    transform: scale(1.1);
  }
}

.btn {
  margin-top: 10rem;
  padding: 20px 100px;
  background-color: rgb(255, 204, 3);
  border-radius: 10px;
  border-style: none;
  box-shadow: 0px 0px 10px black;
  color: blue;
  border: 4px solid rgb(53, 106, 188);
 
  animation-name: grow-shrink;
  animation-duration: 1.07s;
  animation-timing-function: ease;
  animation-fill-mode: backwards;
  animation-direction: alternate;
  animation-play-state: paused;
  animation-iteration-count: infinite;
}

.btn:hover {
  animation-play-state: running;
}
<button class="btn">Play!</button>

Upvotes: 1

SoftViruS
SoftViruS

Reputation: 119

You dont need javascript to create such animation, use css keyframes and infinite animation.

.btn {
    margin-top: 10rem;
    padding: 20px 100px;
    background-color: rgb(255,204,3);
    border-radius: 10px;
    border-style: none;
    box-shadow: 0px 0px 10px black;
    color: blue;
    border: 4px solid rgb(53,106,188);
}

.btn:hover {
  animation: btnPlaying 1s infinite;
}

@keyframes btnPlaying {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}

Upvotes: 0

Related Questions