I have a carousel and I need to reposition the carousel slides based on the current width of the browser. The rules I need to follow are:
browserWidth > 1200: do not reposition slide
browserWidth > 960 && browserWidth < 1200: move slide background X position based
on the formula (25/48*browserWidth)-625
browserWidth < 960: reposition background X position to -125px
I wrote some JavaScript to do this, but whenever I resize the browser the image starts to blink alot. I assume the computer is having trouble trying to re-render the background images since they are such high resolutions. Is there a way to fix this blinking problem?
$(window).resize(function() {
var winW = $(window).width();
if (winW > 960 && winW < 1200) {
$('#' + carouselID).css('left', '600px' );
var leftValue = ((25/48) * winW - 625) + 'px';
var backgroundAtr = 'url(http://www.placehold.it/1200x800) ' + leftValue + ' top no-repeat';
$('#' + carouselID + ' .slides .slide').css('background', backgroundAtr );
} else if (winW <= 960) {
$('#' + carouselID).css('left', '600px' );
var leftValue = '-125px';
var backgroundAtr = 'url(http://www.placehold.it/1200x800) ' + leftValue + ' top no-repeat';
$('#' + carouselID + ' .slides .slide').css('background', backgroundAtr );
} else if (winW >= 1200) {
$('#' + carouselID).css('left', '50%' );
var leftValue = 'left';
var backgroundAtr = 'url(http://www.placehold.it/1200x800) ' + leftValue + ' top no-repeat';
$('#' + carouselID + ' .slides .slide').css('background', backgroundAtr );
}
});
I would suggest putting the resize code inside a
timeout. Some browsers like to fire multiple resize events, which could be what is causing the flashing to occur. Try something like this:This will first clear a timeout, if there is one. Then it will set your resize code to execute in 10ms time. This should give the browser enough time to catch its breath, and stop firing multiple resize events – its basically a debounce function.