Random Background Color Generator. Javascript Project For Absolute Beginners.
Hi everyone. I'm Fidan. I'm a front-end developer. In the front-end learning path, after learning HTML and CSS, we learn Javascript. After learning the basics, we should start practice aka build stuff. But as a beginner, I know everyone gets stuck at: "What should I do? What can I build?" That's why I think the best 1st "project" you should build with JS is a "Random Color Generator". You will practice some of the key elements of DOM
, eventListeners
, Math
objects, etc.
I will explain every single line of the code from HTML to JS, so you can clearly understand. I want you to read carefully once, open a Codepen tab and start doing every single line with me. After 1 or 2 days I want you to do it again, but without looking at the article to see if you really understand it or not. So, let's go.
Random Color Generator:
Final result.
Firstly, let's start with HTML. I will write this on Codepen. But you can choose any online editor you want.
We need h1
for the text "Background Color", a span
for the name of the background color inside h1
, and the button
"Click Me!". Firstly let's create a div
to contain all elements(h1
, span
, and button
) and give it a class name "container"
(or whatever you want).
Open your editor, and try with me.
<div class="container"></div>```
So as you can see nothing changed. With `div` we created a box. But this box doesn't have a width, height, or border. So without content, we can not see it on the screen. But trust me it is there.
Let's write `h1`, `span`, and `button` inside the `div`.
```html
<div class="container">
<h1>Background Color: <span>White</span></h1>
<button>Click Me!</button>
</div>```
Perfect!
But it is ugly, let's make it a bit better. For this we need CSS.
Let's make them all in the center, so we can see them easily. For this, we'll use flexbox.
We want the `container` to be in the center, so we'll add `flexbox` to its parent element, which is `body` in this case
```css
body{
display: flex;
}```
In order to center it horizontally, we'll use
```css
justify-content: center;
For the vertical
align-items: center;
But we have a problem. It is horizontally centered but not vertically. Why is that? Let's give a border to the body
, so we can clearly see what it looks like
body{
border: 1px solid green;
}
So it is more clear now. As you can see it is not vertically centered because the body
doesn't have any height. So we will give height
to the body
.
body{
min-height:100vh;
}
This is a good practice, always make sure to give min-height:100vh
to the body
before writing any CSS. I will deeply explain global styles, and why I used min-height
instead of height
in another blog post.
So as you can see it is perfectly centered on the screen. But the h1
, span
, and button
are not centered. Because we added flexbox
to the body
which is the parent of the div
(in our case). It only affects the position of the direct child element(s), not the elements in it. In order to center h1
, span
, and button
, we should add flex
to the div
"container"
this time. You guessed it correctly because it is the parent of the h1
, span
, and button
.
.container{
display: flex;
align-items: center;
justify-content: center;
}
But we have a problem again, this time the elements are in a row.
This is the default behavior of flex
. It will make elements in a row. In order to make them be on the column
, we should change flex-direction
to the column
.
.container{
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
It is getting better. Let's delete the border
, we don't need it anymore. But always remember this trick, it will help to see things visually when you get stuck.
The button
, as you can see on the finished project has a transparent background, different color, and border color, bigger and a bit wider than our button. Let's change it.
button{
background-color: transparent;
border: 2px solid rgb(37, 150, 190);
color: rgb(37, 150, 190);
font-size:1.2rem;
padding:10px 15px;
cursor: pointer;
}```
**Perfect!**
We are done with HTML and CSS. So let's jump to JS.
First things first, what do we need?
We need to change the background color when we click the button, and we want to see the name of the color on the screen.
Let's create a variable for `button` and `span`. We'll use [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model).
```javascript
let button = document.querySelector('button')
let colorName = document.querySelector('span')
We have just one button, so I used querySelector
. If we had several different styled buttons
, I would give each of them a class name
or an id
, and use getElementByClassName
or getElementById
. We also need colors in order to change the background color
.
let colors = ['red', 'green', 'olive', 'purple']
We need to add eventListener
to the button
so when we click it, it would run a function
.
button.addEventListener('click', changeBackground)
changeBackground
is our function
. Let's create it.
function changeBackground() {
}
We want the change the body-background
to one of the colors in the colors
variable randomly. For choosing it randomly we will use the Math.random()
method. Math.random()
gives us a number greater than or equal to 0 and less than 1 but it never gives us 1, the max number is 0.999... But we don't want any random number, we want it to select how many number the colors
variable has. Let's store it in a variable, so we can use it later. So we add
function changeBackground() {
let randomNumber= Math.random()*colors.length
}
Now it will give us random numbers between 1-3.9999. In order to make it integer, we can wrap them in Math.floor()
.
function changeBackground() {
let randomNumber = Math.floor(Math.random() * colors.length)
}
After that,
function changeBackground() {
let bgColor = document.body.style.backgroundColor = colors[randomNumber]
}
What we did here? We created a variable named bgColor
, and we used DOM
to select body-background
, and we made it equal to colors[randomNumber]
.
If you try, you can it works. Yayy.
But, wait a minute.
I want to see the name of the color on the screen. It only shows white but the background is not white anymore.
Don't worry.
We created a variable named colorsName
for span
. Right?
We can simply change its textContent
to equal the color of the background aka bgColor
.
function changeBackground () {
let randomNumber = Math.floor(Math.random() * colors.length)
let bgColor = document.body.style.backgroundColor = colors[randomNumber]
colorName.textContent= bgColor
}
PERFECT!
That's it.
Hope you enjoyed it. If you have any questions, you can ask me anytime.
The cover image is from plantpot.works
Subscribe to my newsletter
Read articles from Fidan Tehmezli directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Fidan Tehmezli
Fidan Tehmezli
I'm a front-end developer. I'm learning a new thing every single day. I would love to share my knowledge. Hope you like it.