< BACK TO COMPONENTS

Creating a QR Code Generator with HTML, CSS, and JavaScript (Source Code)

Faraz

By Faraz -

Learn how to create a QR code generator using HTML, CSS, and JavaScript in this step-by-step guide. Build your custom QR code solution today.


Creating a QR Code Generator with HTML, CSS, and JavaScript.jpg

In today's digital age, QR codes have become a ubiquitous part of our lives. These versatile barcodes can store a wealth of information and are used for a variety of applications, from product labels to contactless payments. In this blog post, we will show you how to create your very own QR code generator using the power of HTML, CSS, and JavaScript.


Understanding QR Codes


Before diving into the technical details, it's essential to understand what QR codes are and how they work. QR stands for "Quick Response," and these codes can store data in two dimensions. They are scanned using a smartphone or specialized QR code reader, instantly providing the embedded information.


To create a QR code generator, you'll need to grasp the fundamentals of QR code structure and encoding. We'll guide you through each step to ensure a complete understanding.

Source Code

Step 1 (HTML Code):

To begin building your QR code generator, you need a solid HTML foundation. Start by creating the necessary HTML structure, including the input field for user data and a button to trigger the code generation. You should also consider implementing a responsive design to ensure your generator works seamlessly across different devices.


  1. Create an HTML form to accept user input.
  2. Add an HTML button to initiate the code generation process.

Let's break down the code step by step:


1. <!DOCTYPE html>: This declaration specifies that the document is written in HTML, and it is the HTML5 standard.


2. <html lang="en">: This is the opening tag for the HTML document. The lang attribute is set to "en," indicating that the page is written in English.


3. <head>: This section contains meta information and references to external resources that are important for the document but not visible to the user.


  • <meta charset="UTF-8">: This meta tag specifies that the character encoding for the document is UTF-8, which is a widely used character encoding for handling various languages and special characters.
  • <meta http-equiv="X-UA-Compatible" content="IE=edge">: This meta tag is often used for specifying compatibility settings for Internet Explorer.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: This meta tag is used to ensure proper scaling on mobile devices by setting the viewport width to match the device width and setting the initial zoom level to 1.0.
  • <title>QR Code Generator</title>: This sets the title of the web page, which appears in the browser's title bar or tab.
  • <link rel="stylesheet" href="styles.css">: This links an external stylesheet (CSS file) named "styles.css" to the HTML document. It's used for styling the content on the page.

4. <body>: This is the main content of the web page that is visible to users.


5. Inside the <body> tag, there are two main sections:


6. <div class="user-input-section">: This is a container for the user input section of the web page.


7. Inside this container, there are two sections:


8. <section class="heading">: This section contains the heading of the page.


  • <div class="title">QRcodes</div>: This is the main title of the page, which reads "QRcodes."
  • <div class="sub-title">Generate QRCode for anything!</div>: This is a subtitle that provides a brief description of the page's purpose.

9. <section class="user-input">: This section contains user input elements.


  • <input type="text" placeholder="Type something..." name="input_text" id="input_text" autocomplete="off">: This is a text input field where users can type something. It has a placeholder text, a name attribute ("input_text"), and an ID ("input_text") for identifying the input field in JavaScript. The autocomplete="off" attribute disables browser-based autocompletion.
  • <button class="button" type="submit">Generate</button>: This is a button with the class "button" that users can click to generate a QR code.

10. <div class="qr-code-container">: This is a container for displaying the generated QR code.


  • Inside this container, there is a <div class="qr-code"> element. This is where the generated QR code will be displayed.

11. After the user input and QR code containers, there are two <script> tags:


  • <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>: This references an external JavaScript file for generating QR codes. It's using a CDN (Content Delivery Network) hosted JavaScript library.
  • <script src="script.js"></script>: This references another external JavaScript file named "script.js," which is responsible for handling user interactions and generating the QR code based on the user's input.

Step 2 (CSS Code):

A visually appealing and user-friendly interface is vital for an effective QR code generator. CSS comes into play here as it allows you to style your form, button, and the generated QR code.


  • Apply CSS styles to enhance the visual appeal of your form and button.
  • Ensure your design is responsive for various screen sizes.

Let's break down the code step by step:


1. :root:


  • This pseudo-class represents the highest-level parent in the document, typically the <html> element.
  • font-size: 62.5%; sets the base font size to 62.5% of the parent element's font size. This is often used for easier font size calculations later in the CSS, making 1rem equal to 10px.

2. *:


  • Selects all elements in the HTML document.
  • margin: 0; and padding: 0; remove default margin and padding from all elements.
  • box-sizing: border-box; sets the box model to "border-box," which includes the border and padding within the element's dimensions.
  • text-size-adjust: none; and -webkit-text-size-adjust: none; disable text size adjustment for mobile devices.

3. button:hover:


  • Selects button elements on hover.
  • cursor: pointer; changes the cursor to a pointer hand when hovering over buttons, indicating interactivity.

4. body:


  • Selects the <body> element.
  • display: flex; makes the body a flex container, allowing for flexible layout options.
  • align-items: center; and justify-content: center; center the content both vertically and horizontally.
  • background-color: #2b303a; sets the background color of the body to a dark gray.
  • height: 100vh; sets the height to 100% of the viewport height.

5. @media screen and (max-width: 50em):


  • This is a media query that applies styles when the screen width is 50em or less (responsive design for smaller screens).
  • Inside this media query, the styles for the body are adjusted:
  • flex-direction: column; changes the flex direction to a column layout.
  • height: 100%; sets the height to 100% of the viewport height.

6. .heading:


  • Selects elements with the class "heading."
  • margin: 3rem 0 5rem 0; sets margins for the top, right, bottom, and left sides of these elements.

7. .title and .sub-title:


  • Select elements with classes "title" and "sub-title."
  • font-size, font-family, and color properties define the text styles for these elements. "Poppins" is the chosen font, and colors are set.

8. .user-input-section:


  • Styles for a section with the class "user-input-section."
  • Sets display, width, and alignment properties.

9. .user-input:


  • Styles for elements with the class "user-input."

10. .button:


  • Styles for elements with the class "button."
  • Sets styles for buttons, including background color and padding.

11. .qr-code-container:


  • Styles for a container with the class "qr-code-container."

12. .qr-code:


  • Styles for a container with the class "qr-code."

13. .qr-code button:


  • Styles for buttons within the "qr-code" container.

14. .qr-code button a:


  • Styles for links within the buttons inside the "qr-code" container.
:root {
  font-size: 62.5%;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  text-size-adjust: none;
  -webkit-text-size-adjust: none;
}

button:hover {
  cursor: pointer;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #eae6e5;
  background-color: #2b303a;
  height: 100vh;
}
@media screen and (max-width: 50em) {
  body {
    flex-direction: column;
    height: 100%;
  }
}
body .heading {
  margin: 3rem 0 5rem 0;
}
body .title,
body .sub-title {
  font-size: 4rem;
  text-align: center;
  font-family: "Poppins", sans-serif;
  color: #12130f;
  color: #eee5e9;
}
body .sub-title {
  font-size: 1.5rem;
  color: #eee5e9;
  opacity: 0.5;
}
body .user-input-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 40%;
}
@media screen and (max-width: 50em) {
  body .user-input-section {
    width: 100%;
    margin: 2rem 0 0 0;
  }
}
body .user-input-section .user-input {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}
body .user-input-section .user-input label {
  font-size: 1.5rem;
  font-family: "Poppins", sans-serif;
}
body .user-input-section .user-input input {
  width: 80%;
  max-width: 35rem;
  font-size: 16px;
  outline: none;
  border: none;
  border-radius: 0.5rem;
  background-color: #666666;
  padding: 1.5rem 1rem;
  margin: 1rem 1rem 2rem 1rem;
  color: #fff;
}
body .user-input-section .user-input input::placeholder {
  color: #fff;
}
body .button {
  outline: none;
  border: none;
  border-radius: 0.5rem;
  padding: 1.5rem 2.5rem;
  margin-bottom: 3rem;
  background-color: #5b92799d;
  background-color: #92dce5;
  color: black;
  font-family: sans-serif;
  font-size: 1.6rem;
}
button:hover{
  opacity: .7;
}
body .qr-code-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 40%;
}
@media screen and (max-width: 50em) {
  body .qr-code-container {
    width: 100%;
    margin: 8rem 0;
  }
}
body .qr-code-container .qr-code {
  display: flex;
  border-radius: 1rem;
  background-color: #7c7c7c33;
  width: fit-content;
  flex-direction: column;
  justify-content: space-between;
  padding: 2rem;
}
body .qr-code-container .qr-code button {
  display: flex;
  justify-content: center;
  background-color: #1f1f1f;
  color: #eae6e5;
  border: none;
  outline: none;
  width: 100%;
  margin-top: 2.5rem;
  border-radius: 1rem;
}
body .qr-code-container .qr-code button a {
  font-family: sans-serif;
  font-size: 1.5rem;
  width: 100%;
  height: 100%;
  text-decoration: none;
  color: #eae6e5;
  padding: 1rem;
} 

Step 3 (JavaScript Code):

The heart of your QR code generator lies in JavaScript. This is where you'll integrate the QR code generation library to create QR codes from the user's input. We'll recommend using a reliable JavaScript library for this purpose.


  1. Import a QR code generation library into your project.
  2. Write JavaScript code to generate QR codes from user input.

Let's break down the code step by step:


1. The code starts by selecting two elements from the HTML document using their CSS classes and assigning them to variables:


  • The "btn" variable is assigned the element with the CSS class "button".
  • The "qr_code_element" variable is assigned the element with the CSS class "qr-code".

2. An event listener is added to the "btn" element to listen for a click event. When the button is clicked, the code within the arrow function is executed.


3. Inside the event listener, the code checks if the input field (with the id "input_text") has a non-empty value. If it does, it proceeds to generate a QR code. If not, it logs "not valid input" to the console and hides the "qr_code_element" by setting its style to "display: none".


4. The generate function is then called, passing the "user_input" as an argument.


5. The generate function is defined:


  • It makes the "qr_code_element" visible by setting its style to an empty string.
  • It uses the QRCode library (presumably included in your project) to generate a QR code inside the "qr_code_element" div. The text for the QR code is taken from the user's input.
  • A "Download" button is created and appended as a child element to the "qr_code_element".
  • A download link is created as an anchor element ("a") and set to download the generated QR code as "qr_code.png".
  • The download link is appended as a child to the "download" button.
  • The code then checks if there is an existing QR code image or a canvas. If there is an image, the download link is set to the image's source. If not, it waits for 300 milliseconds and then sets the download link to the canvas's data URL.

6. Finally, the generate function is called once with a sample URL (https://codepen.io/coding_dev_) to generate an initial QR code.

let btn = document.querySelector(".button");
let qr_code_element = document.querySelector(".qr-code");

btn.addEventListener("click", () => {
  let user_input = document.querySelector("#input_text");
  if (user_input.value != "") {
    if (qr_code_element.childElementCount == 0) {
      generate(user_input);
    } else {
      qr_code_element.innerHTML = "";
      generate(user_input);
    }
  } else {
    console.log("not valid input");
    qr_code_element.style = "display: none";
  }
});

function generate(user_input) {
  qr_code_element.style = "";

  let qrcode = new QRCode(qr_code_element, {
    text: `${user_input.value}`,
    width: 180, //128
    height: 180,
    colorDark: "#000000",
    colorLight: "#ffffff",
    correctLevel: QRCode.CorrectLevel.H
  });

  let download = document.createElement("button");
  qr_code_element.appendChild(download);

  let download_link = document.createElement("a");
  download_link.setAttribute("download", "qr_code.png");
  download_link.innerHTML = `Download`;

  download.appendChild(download_link);

  let qr_code_img = document.querySelector(".qr-code img");
  let qr_code_canvas = document.querySelector("canvas");

  if (qr_code_img.getAttribute("src") == null) {
    setTimeout(() => {
      download_link.setAttribute("href", `${qr_code_canvas.toDataURL()}`);
    }, 300);
  } else {
    setTimeout(() => {
      download_link.setAttribute("href", `${qr_code_img.getAttribute("src")}`);
    }, 300);
  }
}

generate({
  value: "https://codepen.io/coding_dev_"
});

Final Output:

Creating a QR Code Generator with HTML, CSS, and JavaScript.gif

Conclusion:

In this blog post, we've walked you through the process of creating your own QR code generator using HTML, CSS, and JavaScript. By following these steps and understanding the basics of QR codes, you can develop a user-friendly tool that serves various purposes.


Start building your custom QR code generator today, and unlock the possibilities of QR codes in your web development projects. With the knowledge gained from this guide, you're well on your way to mastering web-based QR code generation.


Credit: Tilak

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post