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").hover(
function () {
var scroll_offset = parseInt($('#content').css('margin-left'));
sliderInt = self.setInterval(function(){
$content.css({'margin-left':scroll_offset+'px'});
scroll_offset--;
},8);
},
function () {
clearInterval(sliderInt);
}
);
Obviously I am running this function every 8ms, which is asking a lot. I'm already cacheing my selectors, so I don't know what I can do to improve performance. Am I just going about it the wrong way?
function play () {
$('#ball').animate({left: '+=20'}, 100, 'linear', play);
}
function pause () {
$('#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%;
}
<div id="bar">
<div id="ball"></div>
</div>
<script src="//code.jquery.com/jquery-3.1.0.js"></script>
This is really simple without the setInterval or even setTimeout.
.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.stop()
to prevent animation buildups.hover
method.and toggling play/pause classes using jQuery:
function play() {
$('#ball').addClass("play").removeClass("pause");
}
function pause() {
$('#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; }
}
<div id="bar">
<div id="ball"></div>
</div>
<script src="//code.jquery.com/jquery-3.1.0.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With