Salman
Salman

Reputation: 431

How to use the animation correctly with class binding in vue?

I am trying to show a zoom effect and with an animation when I hover mouse over an image. I am using vue's class binding (which can be seen below after the problem definition). The problem is that I get the image zoomed with an animation but then the the zoom class gets called again and I see a zoomed image again if I don't move my mouse away from the image.

I have tried different animations but the same problem exists and transition also does not seem to work.

<v-avatar>
      <img v-if="img" :src="img" :class="{ zoom: hover }" alt="" />
</v-avatar>
@keyframes change {
  0% {
    transform: scale(0) translateX(0px);
  }
  100% {
    transform: scale(2.8) translateX(40px);
  }
}

.zoom {
  max-width: 100%;
  height: auto;
  border-radius: 10%;
  box-shadow: 1px 1px 4px 0px rgba(0, 0, 0, 0.5);
  animation: change 1s;
}

I expect to see the zoom behavior with an animation, but the zoom class should not be called again while the mouse is still over the avatar. So that would mean that I want the zoom effect to be shown only once, on a mouse hover.

Upvotes: 1

Views: 327

Answers (2)

aworkinghuman
aworkinghuman

Reputation: 170

I used two classes in my stylesheet (which can also be used in the component itself instead). One transition scales to 1.1 and the other scales to 1. This was because hovering off of the img was very jarring as it zoomed in smoothly but instantly returned to normal size off of img.

HTML:

<img src="./assets/flower.jpg"
@mouseover="hover = true"
@mouseleave="hover = false" :class="{zoomPicture: hover, zoomOutPicture: !hover}">

Data inside the component:

  data() {
    return {
      hover: false,
    }
  }

CSS:

.zoomPicture {
  -webkit-transform: scale(1.1);
    transform: scale(1.1);
    -webkit-transition: .4s ease-in;
    transition: .4s ease-in;
}

.zoomOutPicture {
  -webkit-transform: scale(1);
    transform: scale(1);
    -webkit-transition: .3s ease-in;
    transition: .3s ease-in;
}

So when the mouse isn't on the img, hover is false. This means the class "zoomOutPicture" is active, but won't change the img as it is already at the scale of 1. Then when the user has their mouse over the img, hover becomes true and the image scales to 1.1. When they move the mouse off, hover becomes false and the img smoothly scales to 1 again, so it doesn't look as jarring as earlier now the zoomOutPicture class is used.

Upvotes: 0

Emīls Gulbis
Emīls Gulbis

Reputation: 2070

You should use css :hover selector not animation keyframes to achieve zoom on mouse over (hover)

.image {
  border-radius: 10%;
  box-shadow: 1px 1px 4px 0px rgba(0, 0, 0, 0.5);
  transition: 0.4s transform;
}

.image:hover {
  transform: scale(2.8) translateX(40px);
}
<img src="https://picsum.photos/id/237/200/300" class="image" />

Upvotes: 2

Related Questions