treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Jquery save backgroundColor of current Element in a variable

  • howdy,

    i have this piece of code which works fine:
    $(\"#sidebar ul li ul li a\").mouseover(function() {
    $(this).stop().animate({backgroundColor:'#ccc'},300);
    })
    .mouseout(function (){
    $(this).stop().animate({backgroundColor:'#fff'},100);
    })


    However all #sidebar ul li ul li a-Elements get their backgroundColor assigned randomly by a script i did.
    So actually i don't want to assign a white backgroundColor on mouseot, i want the original-color the element had bevor i mouseoverd.

    So is there a way to query the current backgroundColor of an Element and save it to a variable?

    Something like this - Pseudocode:
    $(\"#sidebar ul li ul li a\").mouseover(function() {

    //i want to save the currentcolor of the object on mouseover
    $current_color = $(this).backgroundColor;
    $(this).stop().animate({backgroundColor:'#ccc'},300);
    })
    .mouseout(function (){
    //i want to assign the original Color (current_color) on mouseout again
    $(this).stop().animate({backgroundColor:$current_color},100);
    })


    Of course this is not working because it is Pseudocode, but maybe there is a solution?
  • it is working with this:

    var bgcol = $(this).css('backgroundColor'); 
    alert (bgcol);


    rgb(204, 204, 204)

    However i always get a RGB value. How can i convert that to a normal Hex-value? (#FF00FF)???
  • found this via a quick google

    http://www.javascripter.net/faq/rgbtohex.htm

    function RGBtoHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)}
    function toHex(N) {
    if (N==null) return \"00\";
    N=parseInt(N); if (N==0 || isNaN(N)) return \"00\";
    N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
    return \"0123456789ABCDEF\".charAt((N-N%16)/16)
    + \"0123456789ABCDEF\".charAt(N%16);
    }


    all is left is striping the r, g, and b.....


    But.... why cant you just use the rgb value to reset the background color?...... background-color accepts hex / rgb / rgba ect....
  • but the bgcol value returns: "rgb(204, 204, 204)"

    How can i apply this value to my mouseout again?


    var bgcol;
    $(\"#sidebar ul li ul li a\").mouseover(function() {
    var bgcol = $(this).css('backgroundColor');
    $(this).stop().animate({backgroundColor:'#ccc'},300);
    })
    .mouseout(function (){
    $(this).stop().animate({backgroundColor:bgcol},100);
    })


    This is not working?