Skip to content Skip to sidebar Skip to footer

Continuous Animation On Hover (performance)

I've created a jQuery function that scrolls a DIV by decreasing the left-margin of the element. It works, but it's incredibly slow. It eats up 100% CPU in no time :s $('.scroll').h

Solution 1:

functionplay () {
  $('#ball').animate({left: '+=20'}, 100, 'linear', play);
}

functionpause () {
  $('#ball').stop();
}

$("#bar").hover( play, pause );
#bar {
  margin-top: 20px;
  background: #444;
  height: 20px;
}
#bar:hover#ball {
  background: lightgreen;
}

#ball {
  position: relative;
  left: 0;
  width: 20px;
  height: 20px;
  background: red;
  border-radius: 50%;
}
<divid="bar"><divid="ball"></div></div><scriptsrc="//code.jquery.com/jquery-3.1.0.js"></script>

This is really simple without the setInterval or even setTimeout.

  • The only important thing is to know that .animate() accepts a function callback, ideal for our purpose to create loop a function. Make sure to use the linear easing instead of the default 'swing' to make our loop constant.
  • To stop our animations we can use stop() to prevent animation buildups.
  • Simply create 2 functions and use them in your hover method.

Using CSS3

and toggling play/pause classes using jQuery:

functionplay() {
  $('#ball').addClass("play").removeClass("pause");
}

functionpause() {
  $('#ball').addClass("pause"); // don't remove .play here
}

$("#bar").hover(play, pause);
#bar {
  margin-top: 20px;
  background: #444;
  height: 20px;
}
#bar:hover#ball {
  background: lightgreen;
}
#ball {
  position: relative;
  left: 0;
  width: 20px;
  height: 20px;
  background: red;
  border-radius: 50%;
}

.play {
  animation: ball-anim 5s infinite linear;
}
.pause {
  animation-play-state: paused;
}
@keyframes ball-anim {
  0%   { left: 0; }
  50%  { left: calc(100% - 20px); }
  100% { left: 0; }
}
<divid="bar"><divid="ball"></div></div><scriptsrc="//code.jquery.com/jquery-3.1.0.js"></script>

Solution 2:

.animate() is a good way to do it. Example:

$(".scroll").hover(function(){
  $("#content").animate({
    marginLeft: "100px",
  }, 1500 );
});​

Working DEMO

Read the documentation to get the idea how to use it.

Post a Comment for "Continuous Animation On Hover (performance)"