Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to change the color of the background based on mouse position

Tags:

jquery

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.

like image 447
mpn Avatar asked Mar 19 '13 20:03

mpn


People also ask

How do I color code my background?

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.


2 Answers

Probably because you're getting fractions back.

Try:

var $pageX = parseInt(e.pageX / $width,10);
var $pageY = parseInt(e.pageY / $height,10);

jsFiddle example

like image 168
j08691 Avatar answered Oct 06 '22 00:10

j08691


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+")";
like image 32
Coin_op Avatar answered Oct 06 '22 01:10

Coin_op