Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get css background property of gradient element by .css()

I'm trying to switch from gradient background to plain background of an element by using jquery.

For some reasons I can't use toggleClass and othe class methods, so I have to modify css properties of an element - background color in my case.

Problem is, that when I'm trying to receive current background css property, .css() method returns something weird.

I have en element with multiple background (gradient) properties, optimized for different browsers

 .element {
       background: #ce4f57 !important;
       background: -moz-linear-gradient(top, #ce4f57 0%, #b7333b 100%) !important;
       background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ce4f57), color-stop(100%, #b7333b)) !important;
       background: -webkit-linear-gradient(top, #ce4f57 0%, #b7333b 100%) !important;
       background: -o-linear-gradient(top, #ce4f57 0%, #b7333b 100%) !important;
       background: -ms-linear-gradient(top, #ce4f57 0%, #b7333b 100%) !important;
       background: linear-gradient(to bottom, #ce4f57 0%, #b7333b 100%) !important;
       filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ce4f57', endColorstr='#b7333b', GradientType=0) !important;
     }

When I try to receive that property

 $('.element').css('background');

I get this:

 rgba(0, 0, 0, 0) linear-gradient(rgb(206, 79, 87) 0%, rgb(183, 51, 59) 100%) repeat scroll 0% 0% / auto padding-box border-box

JsFiddle

As far as I understand, it's compiled property? Can I get original css by js function? If not pls advise how to write regexp to get first color of gradient, assuming there might be differenet compiled css in different browsers...

like image 988
Prosto Trader Avatar asked Apr 29 '14 18:04

Prosto Trader


1 Answers

If you would like to select the first point (0%) of the gradient you can do so by

var css = $('.element').css('background-image');

Then split it into a RGB value

var gradient = css.split('0%')[0].split('linear-gradient(')[1]

In Chrome and FF it works correctly. You can test it using the following fiddle: http://jsfiddle.net/6hvZT/277/

Update - That will be Cross browser compatible:

$("button").click(function(){    
    var css = $('.element').css('background-image');
    var bg_color;

    if ( css === 'none' ) {
        bg_color = $('.element').css('background-color');
    } else {
        bg_color = css.split('0%')[0].split('linear-gradient(')[1]                  
    }

    $('#css').html(bg_color);
}); 
like image 96
marcjae Avatar answered Nov 15 '22 06:11

marcjae