search
HomeWeb Front-endJS TutorialLet's Create a Random-Color Generator!

Let’s Create a Random-Color Generator!

If you’re new to JavaScript, you have probably learned a lot about how the data types, logic, functions, etc. work. This is good; to use JS in more-complicated projects someday, you need to start with the fundamentals. However, depending on your attention span, you may soon start feeling the strong desire to put your JS skills to work on an actual website. Doing so can be a bit complicated (but not as complicated as Regular Expressions, amirite), but one of the simpler ones you can start with is, you guessed it, a random-color generator. In this article, I’ll take you through the steps I used to build one myself.

1. Add boilerplate HTML



  <meta charset="UTF-8">
  <meta http-equiv="X-UA=Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Random-Color Generator</title>

  <!--Link stylesheets-->
  <link rel="stylesheet" href="./styling.css">
  <link rel="stylesheet" href="./responsive.css">

If you’re using VS Code, you can type '!' into the empty HTML document, then press 'Enter' to add this part (not sure about other text editors) if you didn’t know that already. Below the boilerplate, I added links to the CSS documents I used for this project. I recommend keeping your CSS in a separate file, just so that your HTML file doesn’t get too big & complicated. Since the JavaScript we’ll be writing is not super long, I’ll be adding that directly to the HTML file inside the <script> tag, which you’ll see in step 3. If you wanted to have a separate JS file and link it to your HTML file, you could do this:<br> </script>

<script type="text/javascript" src="main.js"></script>

2. Build the HTML ‘skeleton’

  <div>



<p>Now that we’ve added the boilerplate HTML & linked our CSS documents in the </p>, let’s add the body & build out our HTML. As you can see, the getNewColor() function will run whenever the page loads. More on this function in the following steps.

<p>In the picture above, I add a </p>
<div>, which contains a couple of headers, letting the user know where they are & what to do. I then add another <div>, which contains a <span> tag, which will eventually be populated with a HEX code and will display as text on the page. Next, I insert a button that the user clicks to generate a new HEX code. This is done by the getNewColor() function, which I will explain soon.

<h2>
  
  
  3. Add JavaScript!
</h2>

<p>Now we are at the point where the real magic starts to happen. Are you excited? I can tell. Here’s how you do that:<br>
</p>

<pre class="brush:php;toolbar:false"><script>
  function getNewColor() {
    let symbols = "0123456789ABCDEF";
    let color = "#";

</script>

For a relatively simple program like this, we can accomplish what we need to with only one function, the aforementioned getNewColor() function. For this generator, let’s use HEX codes to determine the color, but using RGB values is also possible.

Let’s first put all the possible HEX characters (integers 0–9 & letters A-F) in the form of a string, into a variable called symbols.

Then, let’s initialize the color variable with a hash mark in the form of a string. This variable will be mutated in the loop described below.

Let’s now make a loop that runs 6 times, since there are 6 values in a HEX code. For every loop iteration, a single random value from the symbols string is added to the variable color, which, if you remember, starts with # in string form. At this point, whenever we call the getNewColor(), we get a new HEX code. Now, let’s apply that code to our HTML page.

In my experience, it’s worked best to put the <script> tag at the end of the <body> tag. Some would vehemently argue otherwise, and they may have a point, but I’m not going to discuss that in this article. Please have a keyboard war in the comment section below if you feel inclined, as it’s good for engagement.</script>

4. Apply JS to HTML file

Cool, we now have a function that gives us a random HEX code. However, this is useless unless we apply it to our HTML. In this case, it’d be nice to change the background of the entire page, so the user can have a preview of the random color, and to put the HEX code in text format, so they can copy it. We’ll first need to define these behaviors in our function:



  <meta charset="UTF-8">
  <meta http-equiv="X-UA=Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Random-Color Generator</title>

  <!--Link stylesheets-->
  <link rel="stylesheet" href="./styling.css">
  <link rel="stylesheet" href="./responsive.css">

Still operating inside the getNewColor() function, we can access the background styling property with the first line of code you see in the above photo. We could have also used backgroundColor, which, by the way, translates to background-color in CSS. In this step, we set the variable color, which we randomly defined in the loop, as the background color for the page.

In the second line of code, we access the previously defined tag by its id, ‘hex’. To add the variable color in text form, we can use the method .textContent, which I’ve used here, or the .innerHTML method, to append color to the tag. See the link at the end of this article to read more on the difference between these. In the way we laid out our HTML above, this text will appear directly above the button so the user can see the exact color displayed & copy it if they want.

Altogether, our JS looks like this:

<script type="text/javascript" src="main.js"></script>

5. Tell the program when to run the function

There’s no point in making a function if we never run it, so let’s now tell our program when our getNewColor() function should be called. In this instance, let’s run getNewColor() whenever the page loads & when the ‘Get New Color!’ button is clicked. Here’s how we do that:

  <div>



<p>Now that we’ve added the boilerplate HTML & linked our CSS documents in the </p>, let’s add the body & build out our HTML. As you can see, the getNewColor() function will run whenever the page loads. More on this function in the following steps.

<p>In the picture above, I add a </p>
<div>, which contains a couple of headers, letting the user know where they are & what to do. I then add another <div>, which contains a <span> tag, which will eventually be populated with a HEX code and will display as text on the page. Next, I insert a button that the user clicks to generate a new HEX code. This is done by the getNewColor() function, which I will explain soon.

<h2>
  
  
  3. Add JavaScript!
</h2>

<p>Now we are at the point where the real magic starts to happen. Are you excited? I can tell. Here’s how you do that:<br>
</p>

<pre class="brush:php;toolbar:false"><script>
  function getNewColor() {
    let symbols = "0123456789ABCDEF";
    let color = "#";

</script>

6. Add styling

You may do this part as you wish or not at all, but here is the styling I used on this project:

// continuing getRandomColor()...
    document.body.style.background = color;
    document.getElementByID("hex").textContent = color;
  


7. Let’s test it out!

If you correctly followed the steps above, a random color will be generated when the page loads, as well as when you click the button. The background of the page will be set to the random color & users can copy the HEX code.


Thanks for reading this far! I hope you found it helpful. Remember, it’s OK to read articles & follow tutorials sometimes, but you should only be doing this to learn concepts. Once you think you’ve got the concepts down pat, try making programs yourself. No, you probably won’t get everything right the first time, but encountering a problem & figuring out how to solve it yourself, using concepts you’ve learned, is the way to becoming a better coder.

If you found this article helpful, I’d appreciate a nice comment or a few claps, so I can know what content people find useful, and so I can focus on writing that content in the future.

As always, happy coding!


See this project in action

Link to this project’s GitHub repo

Link to article on differences between .innerHTML & .textContent

Originally published on Medium for JavaScript in Plain English on August 15, 2022

The above is the detailed content of Let's Create a Random-Color Generator!. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor