Search code examples
javascriptjquerygradientlinear-gradients

Change gradient background colors on mouse move


I'm attempting to have a gradient whose top and bottom colors are changed based on cursor position. The below function works when using $(document.body).css('background','rgb('+rgb.join(',')+')'); to change the background but I cannot seem to get it working with a gradient. The below code is what I have set up for testing in Firefox. I will update the code while I currently try to set it up with options for each browser.

$(window).load(function(){
var $win = $(window),
    w = 0,h = 0,
    top = [],
    bottom = [],
    getWidth = function() {
        w = $win.width();
        h = $win.height();
    };

$win.resize(getWidth).mousemove(function(e) {
    
    top = [
        Math.round(e.pageX/w * 255),
        Math.round(e.pageY/h * 255),
        150
    ];
    
     bottom = [
        Math.round(e.pageX/h * 255),
        Math.round(e.pageY/w * 255),
        150
    ];
    
    $(document.body).css('background: -moz-linear-gradient(top, ('+top.join(',')+'), ('+bottom.join(',')+'))');
}).resize();

});

Solution

  • One problem is that you're using the javascript .css method wrong. It takes two parameters, or an object. So it should be:

    $(document.body).css('background', '-moz-linear-gradient(top, rgb('+top.join(',')+'), rgb('+bottom.join(',')+'))');
    

    or

    $(document.body).css({background : '-moz-linear-gradient(top, rgb('+top.join(',')+'), rgb('+bottom.join(',')+'))'});
    

    Apart from that your code looks largely correct.