Let's have some fun with the element that we created and we're going to have on a key press updating
the background color, and we already saw earlier how we can set a background color.
And in this case, in this lesson, we need to generate a random hex value that we can return back and
use as our background color.
And we're going to do this using JavaScript math.
So taking a value where we've got math, random method and you can see what gets returned back from
math random.
We invoke this function a C, we get a zero decimal and a bunch of characters so we can extend on that
by updating it and applying another.
So stringing another method to it and adding in to string.
And we can specify that if we want to hexadecimal value being returned back, we can specify to string
sixteen Kazaks.
The best decimal is be sixteen and it includes the ABCDE, E and F letters as well as all of the regular
ten digits.
So you can see that now we're getting a hexadecimal return back value and it's still zero decimal and
then that's hexadecimal.
So what we want to do is we want to return back a substring minus six on this.
And what that will do is that will take the last six characters that are available here and return that
information back.
And then, of course, we can utilize that in order to build our random color.
So if we do a substring minus six, it will return back the last six characters from that string.
So we can use that and we can use this formula to generate a random hexadecimal value.
So let's create a function for that to handle this, creating a function.
And we can just call this random color.
And this function is going to return back this value.
And we also need to add in the hash in front of this in order to have it a proper color format.
And when we add it to a number, we're going to return back as a string.
And this is hexadecimal anyway.
So it's been returned back as string value.
So let's listen for the key code that we want attached to it.
And I'm going to press the key C and we get a value of 67.
So adding that in as the key that we're listening for.
So we're listening for key 67.
And what we want to do is take the my block object, select its style, value and background color,
and we're going to equal the background color to whatever is being returned back from random color function.
And you can also in order to run a block of code, you can also use the curly brackets around this.
And because we're all on that same statement line, that's what we didn't have to include them and it
would just simply run the statement after the condition is met so we can try that out.
And now you see that if I press see and let me refresh that and if I press see, you see that the color
of the element is updating and I still have the other functionality where I can move left, I can move
up, I can move right and I can move down.
So all of that functionality is still there.
So go ahead and try this out.
Add in the ability to generate a random color using not random.