Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

William Jaggers
William Jaggers
8,109 Points

Javascript - practice task that i created. I have a couple of questions...

I wanted to try to code a simple operation. Accept a hex number from an input field, and turn a box the color that is entered. I have the elements and Javascript code listed below. My questions are:

  1. inside the getKey function, I can see the box change colors when I hit the colorBox.style.backgroundColor = statement (while tracing the code). But as soon as I exit the function, the color changes back to no color. Why is this happening?

  2. When the user inputs an invalid character, I want to remove it from the number being displayed in the input box. So I tried modifying the number string and updating the value in the element. But this isn't working - it still displays the bad character.

HTML:

   <div id="colorbox"></div>
    <form name="colorForm" > 
       <input type="text" id="colorNum" name="input_num" autofocus placeholder="Enter a hex number" size="20"/>
   </form> 

CSS:

#colorbox {
  height: 100px;
  width: 300px;
  border: 1px solid black;
  text-align: center;
  margin: 0px auto;
}

#colorNum {
  display: block;
  width: 120px;
  border: 1px solid black;
  margin: 10px auto;
  text-align: center;
  padding: 10px;    

Javascript:

function getKey(e) {
    if (!e) e=window.event;

    const colorInput = document.getElementById('colorNum');
    let colorNum = colorInput.value;

    if(e.keyCode == 13 || e.keyCode == 9) {     // if return or tab keys
        if (colorNum.length < 6) {
            for(let i = colorNum.length; i < 6; i++) {      // pad number with trailing zeros
                colorNum = colorNum + "0";
            }
        }
        const hexColorCode = '#' + colorNum;
        const colorBox = document.getElementById('colorbox');
        colorBox.style.backgroundColor = hexColorCode;          // set background color of my box
    } else {
        var key = String.fromCharCode(e.which);
        if ((key < "a" || key > "f" ) && (key < "0" || key > "9")) {
            alert("Hex number must be 0-9 or a-f");
            if (colorNum.length == 0) {
                colorNum = "";
            } else {                    
                colorNum = colorNum.substring(0, colorNum.length);
            }
            colorInput.value = colorNum;                        // remove bad input char from number string
        }
    }
}

var colorInput = document.getElementById('colorNum');
colorInput.onkeypress = getKey;

Thank you for any input that you might have to offer. I'm kinda new at this!

fixed code formatting

3 Answers

Steven Parker
Steven Parker
229,732 Points

The color goes away when the page is reloaded.

The default behavior of a form is to reload the page. You don't need a form because you're not using the submit event. So just remove the form tags.

Your second issue is a bit more complicated. For one thing, if you want to shorten a string, your substr size needs to be one less than the string size. But the real problem is event timing. The keypress event occurs before the character is added to the input box, so the current character won't be added until your handler finishes. So for what you want to do, you won't need to remove anything from the input, you just need to prevent it from being put in. So right after your alert message, add this line to end your handler and abort the rest of the normal key processing:

            return false;

Also, I'm guessing you deliberately wanted to experiment with individual key input. You do know there's way easier ways to accomplish this task, right?

Steven Parker
Steven Parker
229,732 Points

You could handle the input event to check the value every time it's changed. Then you could filter out any non-hex values with something like this:

var goodhex = this.value.replace(/[^0-9a-fA-F]/g, '');

Then if the value doesn't match, replace it with goodhex and issue your warning. Then if you also handle the change event you'll know when the user has finished and redirected focus.

William Jaggers
William Jaggers
8,109 Points

Thanks very much for your input! Your suggestions did indeed resolve the issues. I've had a hard time getting a grasp of input field processing; the sources I have been reading generally give only one usage, that being for form submission. It was my thought that I would need to capture each character in order to control the input, so if there is a better way to be doing that, I would be very interested in hearing about it.

Steven Parker
Steven Parker
229,732 Points

I added a comment onto my answer.

William Jaggers
William Jaggers
8,109 Points

Thanks again Steven. I haven't seen too much about RegEx, but I will look into it some more!