1

Can you please tell me how can I raise the block by clicking on the button, and that it would remain at position -25px?

$('button').click(function() {
  $('.block').addClass('animation');
})
.block {
  width: 100px;
  height: 100px;
  background: green;
}

.animation {
  animation: up 750ms;
}

@keyframes up {
  0% {
    margin-top: 0px;
  }
  100% {
    margin-top: -25px;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="block"></div>
<button>UP</button>
Vans
  • 185
  • 1
  • 8
  • Please revise your post title to ask a clear, specific question in sentence format. See [ask]. You have word soup now. – isherwood Jan 30 '23 at 15:51

2 Answers2

3

You need to add the animation-fill-mode: forwards property to the .animation class rule. That will set the element to the properties of the animation finished state.

Documentation for animation-fill-mode

$('button').click(function() {
  $('.block').addClass('animation');
})
.block {
  width: 100px;
  height: 100px;
  background: green;
}

.animation {
  animation: up 750ms;
  animation-fill-mode: forwards;
}

@keyframes up {
  0% {
    margin-top: 0px;
  }
  100% {
    margin-top: -25px;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="block"></div>
<button>UP</button>
isherwood
  • 58,414
  • 16
  • 114
  • 157
disinfor
  • 10,865
  • 2
  • 33
  • 44
1

Use CSS transforms instead of margins:

$('button').click(function() {
  $('.block').addClass('animation');
})
.block {
  width: 100px;
  height: 100px;
  background: green;
  transform: translateY(0);
  transition: transform 750ms;
}

.animation {
  transform: translateY(-25px);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="block"></div>
<button>UP</button>