Marco Angelo Marco Angelo - 3 months ago 9
Javascript Question

Body style Javascript function seems slow

I have made a little Javascript function that changes the background color of the body. However, it seems very slow and jagged when it is run. Does anyone know why and how can I improve the code so it runs smoother?

Please see JSfiddle for working example: https://jsfiddle.net/2s2e737w/

window.addEventListener('scroll', function() {

var fromTop = window.pageYOffset;
document.body.style.backgroundColor = "rgb("+fromTop/5 + ','+fromTop/2 +','+fromTop/3+")";
});


thanks

Answer

Use integer RGB values only, as decimal values are ignored by the browser and this leads to the perceived delay:

document.body.style.backgroundColor = "rgb(" +
    parseInt(fromTop/5, 10) + ',' +
    parseInt(fromTop/2, 10) + ',' +
    parseInt(fromTop/3, 10) + ")";

Percentage values are also acceptable:

https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#rgb

Comments