1

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 you'll see here: http://jsfiddle.net/tctc91/eQwsE/

I'm not able to get this working with the css method using the same principles though: http://jsfiddle.net/tctc91/Tnc8p/

Thanks!

5 Answers 5

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is a much more efficient method that I didn't think of. Nice!
1

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.

Comments

1

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);
    });
});

Comments

1

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);
        }
    });
});

Comments

1

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.