This is an coding problem I was asked at an interview a year ago. I understood the concept during the interview, I knew what I had to do, but I didn't code it right in the 30 minutes and I failed the interview.
I did it in five minutes this time. See, practice does work!!
Part 1: Here's the deal. Build a color picker. There should be an input where a user can type in a hex color, like #aabbcc. Whatever color is written in the box should be displayed in a div on the screen. So if I type #aabbcc in the input field, I should see a div whose color is #aabbcc.
For this stage, go ahead and have the background color update whenever any change happens to the input box.
Part 2: Change this code to only update the color when the user clicks on a button.
Solution:
Pretty simple, we want an input that listens for either the 'input' event or a button that listens for the 'click' event. Our event handler should read the hex value from the input, and set the div's background color to that value.
HTML:
<input type="text" id="inputBox">
<button id="inputButton">
Pick Color
</button>
<div id="colorBox">
</div>
CSS:
#colorBox{
margin-top:20px;
height:100px;
width:100px;
border: 2px solid black;
background-color:#fff;
}
JAVASCRIPT For Part 2 (for part 1, listen to 'input' event instead of 'click':
var oInput = document.getElementById("inputBox");
var oButton = document.getElementById("inputButton");
var oBox = document.getElementById("colorBox");
oButton.addEventListener('click', updateColor,false);
function updateColor(){
var color = oInput.value;
oBox.style.backgroundColor = color;
}
No comments:
Post a Comment