Search code examples
javascriptjquerycsscolor-picker

Changing color for different elements


in my project I have two buttons that change the color of the entire layout, like font color, background color, hovered color and box shadow color. Now it works like that:

$('#red').click(switchRed);
$('#green').click(switchGreen);
$('#blue').click(switchBlue);

function switchRed() {
    $('.shadow-color').css('box-shadow', '0 0 0 2px #d94d4b, 0 0 0 #d94d4b');
    $('.font-color').css('color', '#d94d4b');
    $('.bg-color').css('background', '#d94d4b');
    $('.hover-color').hover(function(){
        $(this).css('background', '#d94d4b');
    }, function(){
        $(this).css('background', '');
    });
    $('.focus-color').focus(function() {
        $(this).css('box-shadow', '0 0 5px #d94d4b');
    });
    $('.focus-color').blur( function() {
        $(this).css('box-shadow','');
    });
    $('.color-icon').attr('src', 'img-v4/dl-button-red.png');
}

function switchGreen() {
    $('.shadow-color').css('box-shadow', '0 0 0 2px #86aa66, 0 0 0 #86aa66');
    $('.font-color').css('color', '#86aa66');
    $('.ui-tooltip-content').css('box-shadow', '0 0 0 5px #86aa66');
    $('.bg-color').css('background', '#86aa66');
    $('.hover-color').hover(function(){
        $(this).css('background', '#86aa66');
    }, function(){
        $(this).css('background', '');
    });
    $('.focus-color').focus(function() {
        $(this).css('box-shadow', '0 0 5px #86aa66');
    });
    $('.focus-color').blur( function() {
        $(this).css('box-shadow','');
    });
    $('.color-icon').attr('src', 'img-v4/dl-button-green.png');
}

It works fine, but if I'd have 4-5 or even more color buttons i'd have to multiply all these functions and my script would be completely unreadable. Could you help me to create a clean and compact script. It should work the next way: We have 2-3 buttons with different color backgrounds. By clicking the button we get it's color attribute and add this color to font, background, hover and so on.


Solution

  • What you're looking for is to create a function with parameters. Functions allow you to pass in a value; the function plugs said value into its inner-workings. In your case you'd be passing in a color value, something like this...

    function setColor(color) {
        $('.shadow-color').css('box-shadow', '0 0 0 2px ' + color + ', 0 0 0 ' + color);
        $('.font-color').css('color', color);
        $('.bg-color').css('background', color);
        etc....
    }
    

    You use the parentheses to pass in one or more parameters (values), and then in the function code you use the names you set for the parameters as placeholders. That way it doesn't matter which color you pass in, it'll just be plugged into all the right spots.

    Then, when you want to use the function, you would just say

    $('#red').click(function () {
        setColor('#d94d4b');
    });
    

    and so on down the line.