Search code examples
javascriptjqueryhtmlcsscolor-picker

Custom jQuery gradient color picker - making it 'user-friendly'


So, I made a very simple custom jQuery gradient color picker, where a user can change certain HTML elements' color to any gradient they want. However, the issue with this is not many people know how to create a gradient. And doing so every time would be a huge hassle. Like, say:

#id {
background: linear-gradient(to right, blue, red);
}

And with that one, a user would have to type in that every time to achieve a gradient of blue -> red in a left -> right direction. Thus, I attempted to create a script that simplified it all. However, as you can see, it doesn't really work.

Basically, I created 3 input boxes: One for the gradient motion (e.g., right, left, etc.), one for the beginning gradient color, and one for the ending gradient color. A user would fill in those values, I would grab them all with .val(), then create one final variable which contained this value:

'linear-gradient(to gradientMotionVariable, beginningGradientColor, endingGradientColor)'

And then, finally, have the div's background property be changed to that variable. I tried searching both Google and SO for this, but couldn't find anything. Any help would be greatly appreciated.


Solution

  • $(document).ready(function () {
        $('#sgCp').click(function () {
            var gM = $('#cGp-motion').val();
            var bC = $('#cGp-bC').val();
            var eC = $('#cGp-eC').val();
            var FGC = 'linear-gradient(to ' + gM + ', ' + bC + ', ' + eC + ')';
            $('#cPr').css('background', FGC);
        });
    });
    

    The problem with your code was that you were passing the css a value that didn't actually use the variable values but passed in the variable names.

    See your:

    var FGC = 'linear-gradient(to gM, bC, eC)';

    Compared to my:

    var FGC = 'linear-gradient(to ' + gM + ', ' + bC + ', ' + eC + ')';