Reputation: 619
I found a sample code which is change the background colour of the body when the user moves the mouse, but the first time the page is white. You can't see the changes until you move the mouse.
var $win = $(window),
w = 0,h = 0,
rgb = [],
getWidth = function() {
w = $win.width();
h = $win.height();
};
$win.resize(getWidth).mousemove(function(e) {
rgb = [
Math.round(e.pageX/w * 255),
Math.round(e.pageY/h * 255),
150
];
$(document.body).css('background','rgb('+rgb.join(',')+')');
}).resize();
JSFiddle: http://jsfiddle.net/WV8jX/
How can I trigger on load?
Upvotes: 1
Views: 3221
Reputation: 1530
Working Example:
$(document).ready(function () {
getRandomColor();
RandomMouseMoveColor();
});
function getRandomColor() {
document.body.style.background = "#"+((1<<24)*Math.random()|0).toString(16);
}
function RandomMouseMoveColor() {
var $win = $(window),
w = 0,h = 0,
rgb = [],
getWidth = function() {
w = $win.width();
h = $win.height();
};
$win.resize(getWidth).mousemove(function(e) {
rgb = [
Math.round(e.pageX/w * 255),
Math.round(e.pageY/h * 255),
150
];
$(document.body).css('background','rgb('+rgb.join(',')+')');
}).resize();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 2
Reputation: 455
You can use such approach:
var $win = $(window),
w = 0,
h = 0,
rgb = [],
getWidth = function() {
w = $win.width();
h = $win.height();
};
function changeColor(e) {
rgb = [
Math.round(e.pageX / w * 255),
Math.round(e.pageY / h * 255),
150
];
$(document.body).css('background', 'rgb(' + rgb.join(',') + ')');
}
$win.resize(getWidth).mousemove(function(e) {
changeColor(e);
}).resize();
$(document).ready(function() {
var is_loaded = false;
$(document.documentElement).bind("mouseover", function(e) {
if (!is_loaded) {
is_loaded = true;
changeColor(e);
}
});
});
Upvotes: 0
Reputation: 429
var $win = $(window),
w = 0,h = 0,
rgb = [],
getWidth = function() {
w = $win.width();
h = $win.height();
};
function colorize(e){
rgb = [
Math.round(e.pageX/w * 255),
Math.round(e.pageY/h * 255),
150
];
$(document.body).css('background','rgb('+rgb.join(',')+')');
}
$win.resize(getWidth).mousemove(colorize).resize();
colorize({pageX:0,pageY:0});
Upvotes: 0