Here is my code:
$(document).mousemove(function(e){
var $width = ($(document).width())/255;
var $height = ($(document).height())/255;
var $pageX = e.pageX / $width;
var $pageY = e.pageY / $height;
$("body").css("background-color", "rgb("+$pageX+","+$pageY+","+$pageX+")");
});
This kind of works, except the mousemove seems to not refresh every time it is moved. It seems to lag, is there some setting that I am missing? The page x and page y are multiplied by the documents relative size to 255, so that the entire spectrum is being used. Thanks.
How to Add Background Color in HTML. To add background color in HTML, use the CSS background-color property. Set it to the color name or code you want and place it inside a style attribute. Then add this style attribute to an HTML element, like a table, heading, div, or span tag.
Probably because you're getting fractions back.
Try:
var $pageX = parseInt(e.pageX / $width,10);
var $pageY = parseInt(e.pageY / $height,10);
jsFiddle example
Your code runs everytime the mouse moves the slightest amount, so its best to keep any code in that event callback to the minimum so it can run as fast as possible to avoid lag. Its therefore better to compute one off things on one occasion only. So something like this would be a little better:
var w = Math.round($(document).width() / 255);
var h = Math.round($(document).height() / 255);
var body = $("body");
$(document).mousemove(function(e){
var pageX = Math.round(e.pageX / w);
var pageY = Math.round(e.pageY / h);
body.css("background-color", "rgb("+pageX+","+pageY+","+pageX+")");
});
If you want the code to respond to different screen sizes then you can simply add a 'resize' event to the document that would reset the w
and h
variables when necessary.
As a side point it might also be quicker to assign the background color natively without jquery:
body.style.backgroundColor = "rgb("+pageX+","+pageY+","+pageX+")";
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