0

I want to make a text box all in javascript no html (so can use it in the console.log), update background color with setInterval. How can it be done?

This is what I got so far, but does not work.

var x = document.createElement("INPUT");
x.setAttribute("type", "text");
x.setAttribute("value", color);
document.body.appendChild(x);
var color;
setInterval(function(){if (x.setAttribute("value",color)===color{document.body.style.backgroundColor=color};},100);
3
  • Why is it important that you use setInterval? Commented Aug 25, 2015 at 13:44
  • because variables are static in JS. Commented Aug 26, 2015 at 12:19
  • I mean, why a timer, when you can just use an event handler to detect changes. With a timer you get lag, and you also have the timer running constantly event when it does't need to do anything Commented Aug 26, 2015 at 12:41

2 Answers 2

1

Try this solution works with timeinterval

var x = document.createElement("INPUT");
x.setAttribute("type", "text");
x.setAttribute("value", color);
document.body.appendChild(x);
var color = '#FFFFFF';
setInterval(function () {
    color = x.value; // you need to get value of color code 
    document.body.style.backgroundColor = color // then it work here
    console.log(color);
}, 100);
Sign up to request clarification or add additional context in comments.

1 Comment

You could at least tidy up your answer if you are to be the accepted one
1

Don't use setInterval to poll the change, instead use the keyup event to detect when the user changes the value:

var color = '#FFFFFF';
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
x.setAttribute("value", color);
document.body.appendChild(x);

x.onkeyup = function(){
    color = this.value;
    document.body.style.backgroundColor = color;
};

Here is a working example

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.