Disable JQuery automatic animation

- 1 answer

Ad

Sometimes when using JQuery to set the css attribute of an element such as "height", "max-height", it automatically binds animation to the change. Sometimes it is awesome, but it is not always necessary. Is there a way to disable this kind of animation?

Actually what is the exact situation that causes JQuery to automatically bind animations? because I don't always see this kind of behavior. I am not using JQuery-UI.

Ad

Answer

Ad

Perhaps the element you are changing the height of has a css transition property that is responsibe for the animation.

$(function() {
  $('.myClass').css('width', '100px');
});
.myClass {
  height: 50px;
  width: 300px;
  background-color: red;
}
.transition {
  transition: width 3s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
with transition
<div class="myClass transition">
</div>

without transition
<div class="myClass">
</div>

Borrowing from What is the cleanest way to disable CSS transition effects temporarily?

You can then create a class that will override the transition property and toggle that class

.notransition {
  -webkit-transition: none !important;
  -moz-transition: none !important;
  -o-transition: none !important;
  -ms-transition: none !important;
  transition: none !important;
}

Note

If you go this route, you may run into the issue of needing to reflow the css

From What is the cleanest way to disable CSS transition effects temporarily? once again:

There are various ways to do this - see here for some. The closest thing there is to a 'standard' way of doing this is to read the offsetHeight property of the element.

One solution that actually works, then, is

$someElement.addClass('notransition'); // Disable transitions
doWhateverCssChangesYouWant($someElement);
$someElement[0].offsetHeight; // Trigger a reflow, flushing the CSS
changes $someElement.removeClass('notransition'); // Re-enable
transitions
Ad
source: stackoverflow.com
Ad