Skip to content Skip to sidebar Skip to footer

Updating Backgroundcolor Live Based Upon An Input Field Value Using Jquery?

I'm building a little script that changes content and css live on the page based upon the values of various input fields. I'm able to change the content 'live' absolutely fine as y

Solution 1:

Replace the second bgColor with $(this).val().

You have assigned the starting value to bgColor, and then you never reassign a new value to it.

jsFiddle.

Solution 2:

You just have to define the bgColor variable after the user inputs it. Here's a fiddle that does just that.

What I've done is copy the bgcolor variable and placed it once again inside the keyup function. This way, it defines the variable again after a key is pressed.

The fiddle works perfectly.

Solution 3:

You're forgetting to re-set the bgcolor variable whenever you change the input:

Try this:

$(function() {
    var bgColor = $('#colorpickerField1').val();   
    $('body').css("backgroundColor",'#' + bgColor);

    $('#colorpickerField1').change(function() {
       var bgColor = $('#colorpickerField1').val();
       $('body').css("backgroundColor",'#' + bgColor);
    });
});

Solution 4:

You have to set bgColor's value again. I also added a little check if it's length is 3 or 6 chars.

$(function() {
    var bgColor = $('#colorpickerField1').val();   
    $('body').css("backgroundColor",'#' + bgColor);

    $('#colorpickerField1').keyup(function() {
       bgColor = $('#colorpickerField1').val();
        if(bgColor.length ==3 || bgcolor.length == 6) {
            $('body').css("backgroundColor",'#' + bgColor);
        }
    });
});

Solution 5:

You need to retrieve the .val() of the field inside the .keyup() handler, as the value will always be changing every time the user presses a key.

Change your javascript to:

$(function() {
    var bgColor = $('#colorpickerField1').val();   
    $('body').css("backgroundColor",'#' + bgColor);

    $('#colorpickerField1').keyup(function() {       
       $('body').css("background-color",'#' + $(this).val());
    });
});

Updated jsFiddle: http://jsfiddle.net/Tnc8p/1/

Post a Comment for "Updating Backgroundcolor Live Based Upon An Input Field Value Using Jquery?"