Grow your CSS skills. Land your dream job.

Jquery save backgroundColor of current Element in a variable

  • # September 22, 2009 at 6:47 am

    howdy,

    i have this piece of code which works fine:

    Code:
    $(“#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:

    Code:
    $(“#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?

    # September 22, 2009 at 8:29 am

    it is working with this:

    Code:
    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)???

    # September 22, 2009 at 12:39 pm

    found this via a quick google

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

    Code:
    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….

    # September 22, 2009 at 12:44 pm

    but the bgcol value returns: "rgb(204, 204, 204)"

    How can i apply this value to my mouseout again?

    Code:
    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?

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".