Search code examples
jqueryvariablestransparencyrgbgradient

Put jQuery variable in css gradient


I have this code which generates the RGB values from a hex code.

            <script>
            var s = "<?php the_field('phpvariableforcolour'); ?>";
            var patt = /^#([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})$/;
            var matches = patt.exec(s);
            var rgb = "rgb("+parseInt(matches[1], 16)+","+parseInt(matches[2], 16)+","+parseInt(matches[3], 16)+");";
            alert(rgb);
            </script>

I want to then apply the rgb variable (which is currently in an alert) to an inline css style where the RGB values appear e.g. rgba(0,0,0,0.0) : -

            background-image: -webkit-linear-gradient(@origin, rgba(0,0,0,0.0), rgba(0,0,0,0.2));
            background-image: -moz-linear-gradient(@origin, rgba(0,0,0,0.0), rgba(0,0,0,0.2));
            background-image: -o-linear-gradient(@origin, rgba(0,0,0,0.0), rgba(0,0,0,0.2));
            background-image: -ms-linear-gradient(@origin, rgba(0,0,0,0.0), rgba(0,0,0,0.2));
            background-image: linear-gradient(@origin, rgba(0,0,0,0.0), rgba(0,0,0,0.2));

I can't see to find a way to do this, with jQuery I can add background-image, but not all these.


Solution

  • You could use the ".css()" function in jQuery.

    http://jsbin.com/vukize/1/edit?js,output

    the HTML I used:

    <!DOCTYPE html>
    <html>
    <head>
      <script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
      <meta charset="utf-8">
      <title>jQuery inline RGB Values</title>
    </head>
    <body>
      <div id="colorObject"></div>
    </body>
    </html>
    

    the jQuery:

    var rgba = "rgba(110,131,37,0.5)";
    var rgbaTwo = "rgba(10,131,37,1)";
    
    $('#colorObject').css({
      'background' : '-webkit-linear-gradient(left,' + rgba + ', ' + rgbaTwo + ')',
      'background' : '-moz-linear-gradient(left,' + rgba + ', ' + rgbaTwo + ')',
      'background' : '-o-linear-gradient(left,' + rgba + ', ' + rgbaTwo + ')',
      'background' : '-ms-linear-gradient(left,' + rgba + ', ' + rgbaTwo + ')',
      'background' : 'linear-gradient(to right,' + rgba + ', ' + rgbaTwo + ')'
    });
    

    edit: Looks like a couple people beat me to it. ;)

    double edit: So, it seems the problem is a semicolon where it shouldn't be if it's being used in a css(); function.

    Change:

    var rgb = "rgb("+parseInt(matches[1], 16)+","+parseInt(matches[2], 16)+","+parseInt(matches[3], 16)+");";
    

    to:

    var rgb = "rgb("+parseInt(matches[1], 16)+","+parseInt(matches[2], 16)+","+parseInt(matches[3], 16)+")";
    

    Now using it as a variable in a css(); function will work.