levipadre
levipadre

Reputation: 619

Change background color on mouse move and page load as well

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

Answers (4)

Prabhat-VS
Prabhat-VS

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

myxobek
myxobek

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

Kalamun
Kalamun

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

nicost
nicost

Reputation: 1040

You can use jquery's $(document).ready() function, which get's called when the content is loaded to initially set a random background-color (or whatever color you want).

I updated your fiddle.

Upvotes: 0

Related Questions