Change Element Color With jQuery

16 Nov 2012

First, create your form. Take note of the Input ID, you're going to use this to identify it in jQuery. Also create an open div as an example.

    <form method="post" action="">
    <label for="textcolor">text color</label>
    <input type="color" class="theme" id="textcolor" size="12"/>
    </form>

    <form method="post" action="">
    <label for="bg">bg color</label>
    <input type="color" class="theme" id="bg" size="12"/>
    </form>

    <form method="post" action="">
    <label for="bordercolor">border color</label>
    <input type="color" class="theme" id="bordercolor" size="12"/>
    </form>

    <div class ="ele">Element</div>

Next, style each enough that you'll be able to see the edits you'll be making.

    .ele {
        width:300px;
        height:200px;
        border-color:#3e3e3e;
        background-color:#e4e4e4;
        color:#ffffff;

    }

Now, add your jQuery.

    $(document).ready(function() {

        /* color picker - border */
        $("#bordercolor").change(function(){
            $("div.ele").css("border-color",$("#bordercolor").val());

        });

        $('#bordercolor').keypress(function (e) {
           if (e.which == 13) {

                e.preventDefault();
                $("div.ele").css("border-color",$("#bordercolor").val());
           }
        });

        /* color picker - text color */
        $("#textcolor").change(function(){
            $("div.ele").css("color",$("#textcolor").val());

        });

        $('#textcolor').keypress(function (e) {
           if (e.which == 13) {

                e.preventDefault();
                $("div.ele").css("color",$("#textcolor").val());
           }
        });


        /* color picker - background */
        $("#bg").change(function(){
            $("div.ele").css("background-color",$("#bg").val());

        });

        $('#bg').keypress(function (e) {
           if (e.which == 13) {

                e.preventDefault();
                $("div.ele").css("background-color",$("#bg").val());
           }
        });




    });


    });

The .css() method will change each color with the value that is given. The extra keypress method just makes the color change when you hit Enter on the keyboard after entering a value. Without that function it will change when you click elsewhere on the page.