Reputation: 1018
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.
Upvotes: 5
Views: 5594
Reputation: 10728
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+")";
Upvotes: 1
Reputation: 207913
Probably because you're getting fractions back.
Try:
var $pageX = parseInt(e.pageX / $width,10);
var $pageY = parseInt(e.pageY / $height,10);
Upvotes: 8