Hosted Project
https://js-beginners.github.io/project_change_color_background/
Github Source Files
https://github.com/JS-Beginners/project_change_color_background
This background color changing app was short and sweet to complete. Since I was given the HTML and CSS assets (really, just the styled BootStrap4 button), all I had to do was create an array of different colors and then add a ‘click' event listener to the button. Once the button was clicked, a different background color would appear.
New things learned or refreshed:
I didn't learn any new JavaScript features during this project but I was refreshed on using JavaScript to style CSS (e.g. element.style.backgroundColor = red;
)
Lines of code:
12 lines of code.
Time to code:
This took about 5 minutes to code.
Biggest take away:
None.
Your Turn!
What to accomplish:
- Download the source code from the github repository above.
- Delete the script.js file.
- Implement the JavaScript code such that every time the button is clicked, the background changes color.
- Add a link to your finished project below!
Hi, There is a problem in changeBackground(). You need to remove the +1 in the 10 line of code. If you don’t remove the +1 you will never get the red color.
//Choose a random color
const button = document.querySelector(‘button’)
const body = document.querySelector(‘body’)
const colors = [‘red’, ‘green’, ‘blue’, ‘yellow’, ‘pink’, ‘purple’]
body.style.backgroundColor = ‘violet’
button.addEventListener(‘click’, changeBackground)
function changeBackground(){
const colorIndex= parseInt(Math.random()*colors.length+1)
body.style.backgroundColor = colors[colorIndex]
}
ha! Thanks, Someone. I fixed it!
I’m doing this challenge along with the udemy course “Modern Javascript From the Beginning” by Traversy Media.
This challenge took me about approximately 45 mins to finish. Even though it took me an long time to do such an simple project I think for an absolute beginner it’s okay. I thought I won’t be able to do this at all so I’m quiet happy.
Github Page: https://swethalakshmi22.github.io/Js-Project1/
Great job, Swetha! Hope you enjoyed it!
Hey can you tell how to run this project? m a beginner in Js
Best way to run my code is to go to the GitHub link and then download the folder in its zip format. Then, extract the folder. Afterwards, you should be able to simply open the index.html file.
If this is all too new for you, I recommend taking Smigla’s course by following the link on this page.
Thanks for sharing this bro, it’s very helpful.
You’re welcome!
Added JS code to produce a random hex number to randomly generate the background every time:
https://bwhatnall.github.io/Change-Background-Color/
Nice!
Thank you for this list, simple projects really help beginners, i just did the first one
https://codepen.io/malmossa/pen/yLYbRLa
Hi jsbeginners,
I found your list looking for ways to really learn and practice JavaScript as a self-taught dev.
I tried for about 30 minutes before giving in that I couldn’t figure it out. Then I copy pasted your solution into my editor and commented it out, and I looked into how I could change my code to make it work. I figured if I can “fix” my code using your solution as a guide, it would be a good way to see just what goes where and why some things weren’t working like I wanted them to.
So here’s what I ended up with after about 20 more minutes of fiddling:
var colors = [“blue”, “red”, “orange”, “grey”, “black”, “white”, “teal”];
function pickRandomBgColor() {
var randomColor = parseInt(Math.random() * colors.length);
document.querySelector(“body”).style.backgroundColor = colors[randomColor];
}
const button = (document.querySelector(“button”).onclick = pickRandomBgColor);
Works just fine when I test it. I realise there’s lots of room for refactoring etc, but it’s already miles from my original code (which was much longer to boot).
Anyway, off to the next one on the list.
Thanks, jsbeginners!
Glad I could help!
Hi – this is not a beginners course. You specifically advise beginners to purchase a course in JavaScript, reiterated in the comments above. What is the thinking behind this? Why do you specifically set up a site called ‘JSBeginners’ which is not a beginners site? Please think about how misleading you are being.
Another awful online resource for JS ‘Beginners’.
I don’t understand your criticism. This site is not a course, but it does provide links to projects that I’ve complete which I feel are for beginners. Feel free to do them or not. It is your choice. Sorry, the site couldn’t help you.
Man this is very childish…i am beginner in js and have been looking for a compiled list of projects to practice and this list is the best list i found online….so stop being an ass and start appreciating what the author did….
This is what I came up with. Great projects btw. I am just beginning and am looking forward to going through all of your projects!
var button = document.getElementById(“button”)
let colors = [“red”, “blue”, “green”, “yellow”, “brown”, “purple”, “teal”, “black”]
function handleClick(){
document.body.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)]
}
button.addEventListener(“click”, handleClick)
Looks great, Chris! Thanks for sharing!
Here is what I came up with:
// choose random color
randomColor = () => {
return “#” + Math.floor(Math.random() * 16777215).toString(16);
};
// Add click Event to button
document.querySelector(“.btn”).addEventListener(“click”, () => {
document.querySelector(“.body”).style.background = randomColor();
});
Here is my solution:
const body = document.querySelector(‘body’);
const button = document.querySelector(‘.btn’)
let colorArray = [‘red’, ‘blue’, ‘pink’, ‘purple’, ‘yellow’, ‘tomato’];
button.addEventListener(‘click’, () => { body.style.backgroundColor = colorArray[Math.floor(Math.random() * colorArray.length)] })
I had fun doing this and it works, but I’m not sure if it’s best practice that I put all the math random wizardry inside of the event listener like that. I tried to do a function before and it didn’t seem to work (at least the way I was doing it) so I tried that and it did.
It’s my first day of the challenge here. I am entry level web developer but I believe I need to take a step back to build my solid fundamental in order to dive deeper into the frameworks.
Here is my Project its a little different
https://001-100-js-projects.glitch.me/001/index.html
Thank You So Much For Helping Us ..
Here my solution:
function randomBackgroundColor() {
let red = (Math.random() * 255).toFixed(0);
let green = (Math.random() * 255).toFixed(0);
let blue = (Math.random() * 255).toFixed(0);
return document.body.style.background = `rgb(${red}, ${green}, ${blue})`;
}
took me a few minutes but after a bit of troubleshooting utilizing my good old friend console.log() 🙂 I came up with this solution.
almost forgot….I obviously called the function inside the button element :
Click Me Dammit!
Thanks for for all your efforts here. Your page is really helpful for self-taught devs.
Much appreciated. Looking forward to the more challenging projects.
Cheers
Nice!
let colors = [‘#ff9ff3’, ‘#feca57’, “#ff6b6b”, “#48dbfb”, “#1dd1a1”, “#00d2d3”, “#54a0ff”, “#5f27cd”, “#c8d6e5”, “#576574”];
const body = document.querySelector(‘body’);
const button = document.querySelector(“button”);
body.style.backgroundColor = ‘#ff9ff3’;
button.addEventListener(‘click’, setRandomColor);
function setRandomColor() {
let randomColors = colors[Math.floor(Math.random() * colors.length)];
body.style.backgroundColor = randomColors;
}
I can see some flaws in your function as a practical example from an analytical perspective:
//Scenario 1: What if the function randomly picks the same color.
Currently, your function would allow this to happen. Even worse the function would update the DOM despite it’s the same value.
To prevent this, need to keep track or check the last color picked so you don’t end up with the same value. There are a lot of ways to implement this.
//Unit Testing
If you would write some tests you can already see the function is not bulletproof. The function should stop running if it has to work with invalid values. This is very important when you have to work with loops to fix scenario 1. You don’t want your function to run and calculate incorrect or undefined values.
Thanks for the feedback!
first app in JavaScript
my solution :
let counter = 0;
btn.addEventListener(‘click’, function (e) {
let colors = [‘red’, ‘green’, ‘blue’, ‘yellow’, ‘pink’, ‘purple’]
e = colors[counter++];
if(counter == colors.length)
{
counter = 0;
}
document.body.style.backgroundColor = e;
});
const changeColorBtn = document.querySelector(‘button’);
changeColorBtn.addEventListener(‘click’, changeColorBtnClick);
function getRandomNumber(max) {
return Math.floor((Math.random() * max));
}
function changeColorBtnClick()
{
var randomColor = `rgb(${getRandomNumber(255)},${getRandomNumber(255)},${getRandomNumber(255)})`;
document.body.style.backgroundColor = randomColor;
}
Day 1 and 1st challange done:
https://codepen.io/iliyan-yordanov/pen/Rwrqvpd
my code:
let theButton = document.getElementById(‘button’);
theButton.addEventListener(‘click’, ()=>{
let colors = [‘red’, ‘blue’, ‘green’, ‘orange’, ‘yellow’, ‘lightblue’];
let randomColor = colors[Math.floor(Math.random() * colors.length)];
document.body.style.backgroundColor = randomColor;})
thanks
That works!
Thanks for the good work, bro. I have been for things like hopefully, I would be able to challenge myself the more into building awesome apps. Bellow is my code.
/* A program to change the background color of a webpage*/
const changeBtn = document.querySelector(“button”);
const body = document.querySelector(“body”);
// Create a list for the colors
const colors = [“green”, “yellow”, “black”, “red”, “blue”];
// Create an initial color for the background
body.style.backgroundColor = “violet”;
changeBtn.addEventListener(“click”, () => {
// Generate random numbers for each color changed
let ranNum = Math.random() * colors.length;
const colorIndex = parseInt(ranNum);
body.style.backgroundColor = colors[colorIndex];
});
Hello Devs, I did it in a different way. It works !
//DECLARE CONSTs
//Get button
const colorBtn = document.querySelector(“.btn”);
//Get body
const body = document.querySelector(“body”);
//Set init background color
body.style.backgroundColor = ‘#429’;
//Trigger an event (click event)
colorBtn.addEventListener(“click”, changeBgColor);
//Declare function
function changeBgColor() {
const colorIndex = parseInt(Math.round(Math.random()*9));
const colorIndex1 = parseInt(Math.round(Math.random()*9));
const colorIndex2 = parseInt(Math.round(Math.random()*9));
//pass the random color index as hexCode
const bgColor = `#${colorIndex}${colorIndex1}${colorIndex2}`;
body.style.backgroundColor = bgColor;
};
here is a fiddle link to my solution.
https://jsfiddle.net/idaraobong/zjL5k06r/2/
https://ashumsd7.github.io/01JS-change-random-backgroud-color/
Thank you for putting the project together. Trying to get to grips with js, started Treehouse, and wanted a bit of practice.
I slightly modified your html, by adding an ID to the button, and making the html and body elements 100% high.
I then created a complete different solution for the js. I’ve created a function which creates a random number between 0 – 255
Then a function that creates a rgb colour value by calling the random number generator.
My button click event listener fires once the button is clicked and calls the function that creates a rgb value.
// My JavaScript Solution
const btn = document.getElementById(‘colour-changer’);
const body = document.querySelector(‘body’);
// generate a random number from 0 to 255
function randomNum() {
return Math.floor(Math.random() * 256 );
}
// build rgb colour value and return string
function colourGen() {
const red = randomNum();
const green = randomNum();
const blue = randomNum();
return `rgb(${red},${green},${blue})`;
}
// click event listener
btn.addEventListener(‘click’, (e) => {
const colour = colourGen();
body.style.backgroundColor = colour;
})
my code is:
myColors = [‘red’, ‘green’, ‘blue’]
i = 0
document.querySelector(‘button’).onclick = function () {
‘use strict’;
document.body.style.backgroundColor = myColors[i]
i++
i == myColors.length ? i = 0 : i = i
}
need your opinion please
Hey. I completed this challenge and managed to do the js in roughly 8-9 lines of code. Have a look at my github and let me know what you think. I like this challenge as it allows me to just go over the basics of JavaScript all over again and I had to really think about this challenge, even though eventually it was really easy to do.
Awesome, Tynesha!
My Code from index.js :
var button = document.getElementById(“btnid”);
var page = document.getElementById(“pageid”);
var randomColors = [“red”,”blue”,”orange”,”blue”,”black”];
//PRESS FOR MAGIC
function getMagic(event)
{
var r = Math.floor(Math.random() * randomColors.length);
page.style.backgroundColor = randomColors[r];
}
hi to you all. this is a solution i came up with. it works but what do you think?
var colors = [
“#FFFF00″,”#808000″,”#00FF00″,”#FFA07A”,”#CD5C5C”
];
var body = $(‘body’);
$(‘button’).on(‘click’, function() {
$(‘body’).css( {
background: colors[Math.floor(Math.random() * colors.length)]
} );
});
$(document).on(‘keyup’, function(event) {
if ( event.which === 27 ) {
body.css({
background: “white”
});
};
});
const body = document.querySelector(‘body’);
const btn = document.querySelector(‘.btn’);
const colors = [
‘gray’,
‘red’,
‘pink’,
‘blue’,
‘yellow’,
‘lightgreen’,
‘orange’,
‘violet’,
‘indigo’,
‘lightblue’
];
const randomNum = (min, max) => {
let rand = Math.random() * max;
return Math.floor(rand);
}
btn.addEventListener(‘click’, () => {
body.style.background = colors[randomNum(0, colors.length)];
})
It took me a bit, but I’m an ultra-noob when it comes to JavaScript. I first touched it last week! Here is mine… I added a ‘a’ value to create a random rgba generating button.
Here is my link:
https://github.com/ttjncarney/project_change_color_background.git
Keep it up!
const body = document.querySelector(‘body’);
const colors = [“red”,”yellow”,”green”,”blue”,”orange”,”pink”]
function switchColor(){
const randomPicker = parseInt(Math.random()*colors.length)
const colorPicked = colors[randomPicker];
console.log(randomPicker);
console.log(colorPicked);
body.style.backgroundColor=colorPicked;
}
i have solved this way
const button = document.querySelector(‘button’)
const body = document.querySelector(‘body’)
let colors = [‘red’, ‘green’, ‘blue’, ‘yellow’, ‘pink’, ‘purple’, ‘violet’]
class BackgroudChange {
constructor(bgColor){
this.bgColor = bgColor
}
colorChange(){
let colorIndex = Math.round(Math.random() * colors.length)
body.style.backgroundColor = colors[colorIndex]
}
}
let backgroundChange = new BackgroudChange(‘indigo’)
body.style.backgroundColor = backgroundChange.bgColor
button.addEventListener(‘click’, backgroundChange.colorChange)
Took a swing at it myself:
//changes color
const button = document.querySelector(“.btn”);
const body = document.querySelector(“body”);
const colors = [“red”, “orange”, “yellow”, “green”, “blue”, “purple”];
const getRandomInt = () =>
Math.floor(Math.random() * Math.floor(colors.length));
button.addEventListener(“click”, () => {
body.style.backgroundColor = colors[getRandomInt()];
});
You got it!
One little change here, I added onclick() event in html file instead adding eventListener in js file.
const body = document.querySelector(‘body’)
body.style.backgroundColor = ‘violet’
const changeBGColor = () => {
const colors = [‘red’,’green’,’blue’, ‘violet’, ‘purple’, ‘pink’]
const colorIndex = parseInt(Math.random()*colors.length);
body.style.backgroundColor = colors[colorIndex]
}
i was trying to make the button to come to the center but i don’t get it and i don’t want to use css
You could use html