Build Your Own Multiplication Table Generator using HTML, CSS, and JavaScript

Faraz

By Faraz -

Learn how to create a dynamic multiplication table generator using HTML, CSS, and JavaScript. A step-by-step tutorial for all skill levels.


Build Your Own Multiplication Table Generator using HTML, CSS, and JavaScript.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Preview
  6. Conclusion

In today's digital age, web development is a dynamic and accessible field that empowers individuals to create interactive tools that serve a variety of purposes. One such tool is the Multiplication Table Generator. This innovative creation allows users to effortlessly generate multiplication tables for any given number, adding a layer of convenience and efficiency to a fundamental mathematical task.

Imagine a scenario where students, teachers, or anyone needing quick multiplication references can access this tool online, without the need for paper or manual calculations. This project not only provides a practical solution but also serves as an excellent opportunity to explore the synergy between three core web technologies: HTML, CSS, and JavaScript.

HTML, or HyperText Markup Language, forms the foundation of web content, allowing us to structure and organize elements on a webpage. CSS, which stands for Cascading Style Sheets, enhances the visual appeal of our creation, ensuring an engaging and user-friendly interface. Finally, JavaScript, a versatile scripting language, adds the magic of interactivity, enabling us to create dynamic content and respond to user actions.

Throughout this comprehensive guide, we'll break down the process of building the Multiplication Table Generator into manageable steps. Whether you're a coding novice taking your first steps into web development or a seasoned programmer looking to expand your skill set, this tutorial has something to offer. By the end of this journey, you'll not only have a functional multiplication table generator but also a deeper understanding of how these technologies collaborate harmoniously to deliver an exceptional user experience.

As we embark on this journey together, keep in mind that the Multiplication Table Generator is just a starting point. The concepts and techniques you'll master can be extended to other projects, allowing you to unleash your creativity and build even more sophisticated web applications. So, let's dive into the world of web development and create something incredible – a Multiplication Table Generator that demonstrates the power and beauty of HTML, CSS, and JavaScript working in harmony.

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our Multiplication Table Generator.

After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

Let me break down the code for you:

1. <!DOCTYPE html>: This declaration specifies that the document is an HTML5 document.

2. <html lang="en">: The <html> tag indicates the beginning of the HTML document. The lang attribute specifies that the document is in English.

3. <head>: The <head> section contains metadata and external resources used by the page, such as stylesheets and scripts.

  • <meta charset="UTF-8">: Sets the character encoding to UTF-8, which supports a wide range of characters and languages.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: Specifies the viewport settings for responsive design on various devices.
  • <meta http-equiv="X-UA-Compatible" content="ie=edge">: Sets the compatibility mode for Internet Explorer.
  • <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">: Links to the Bootstrap CSS framework.
  • <link href="https://fonts.googleapis.com/css2?family=Source+Serif+Pro:wght@300&display=swap" rel="stylesheet">: Links to a Google Font for styling.
  • <link rel="stylesheet" href="styles.css">: Links to an external CSS file named "styles.css."
  • <title>Multiplication Table Generator</title>: Sets the title of the web page displayed in the browser's title bar.

4. <body>: The <body> section contains the visible content of the web page.

5. <div class="container">: A Bootstrap container for content alignment and padding.

6. <section>: A semantic HTML5 element to define a section of content.

7. <h3 id="title" class="text-center">Multiplication Table Generator</h3>: An <h3> heading with the ID "title" and centered alignment.

8. <p style="text-align:center;font-size:12px;margin-bottom: 50px;margin-top: -30px;">...: A paragraph of text centered, with font size, margin adjustments. It provides a brief description of what the tool does.

9. <form onsubmit="return false">: A form element with a JavaScript event to prevent the form from submitting.

  • Two input fields for users to enter the number and range for generating the multiplication table.
  • <input type="submit" id="btnGenerate" value="Get Table">: A submit button to trigger table generation.

10. <div id="ans"></div>: An empty <div> where the generated multiplication table will be displayed.

11. <script src="script.js"></script>: Links to an external JavaScript file named "script.js" for interactivity.

This is the basic structure of our Multiplication Table Generator using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the Multiplication Table Generator is in place, the next step is to add styling to the Generator using CSS.

Next, we will create our CSS file. In this file, we will use some basic CSS rules to create our Generator.

1. The code begins by importing a font from Google Fonts, specifically the 'Source Serif Pro' font with a weight of 300. This imported font will be used for the text on the webpage.

2. The overall design starts by setting the font family for the entire body of the webpage to 'Source Serif Pro', which is a serif font type. The text color is a light shade of gray, and the background color of the page is a pale gray tone.

3. The content is contained within a "container" element. This container has a small amount of space at the top, a maximum width of 500 pixels, and is horizontally centered on the page.

4. Inside the container, there is a section element representing a distinct section of content. This section has a dark blue background color and a font size of 1.2em, making the text slightly larger than the default size. The text within the section is centered, and the corners of the section have a rounded appearance due to a border-radius of 15 pixels.

5. The element with the ID "title" has an extra margin at the bottom and the text is transformed to uppercase. Similarly, the element with the ID "ans" has a bit of margin at the top, a deep purple background color, and bold font weight.

6. There's a button with the ID "btnGenerate" that occupies 50% of its parent's width and has a height of 40 pixels. It features a background color of dark purple and is surrounded by a border with rounded corners. The text color is white, and the text itself is displayed in uppercase. When hovered over, the button's background color changes to a slightly darker shade.

7. Lastly, there's a specific style applied to an element with the ID "generate" that's found within a form element within the container's section. It adds padding to this element, giving it some spacing.

This will give our Multiplication Table Generator an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

@import url('https://fonts.googleapis.com/css2?family=Source+Serif+Pro:wght@300&display=swap');

body {
    font-family: 'Source Serif Pro', serif;
    color: rgb(248, 248, 248);
  background-color: #ececec;
}
.container {
    padding-top: 4%;
    max-width: 500px;
    margin: 10px auto;
    
}

section {
  background: #0a0e31;
    font-size: 1.2em;
    text-align: center;
    border-radius: 15px;
}

#title {
    margin-bottom: 30px;
    text-transform: uppercase;
}

#ans {
    margin-top: 2%;
    background-color: #512DA8;
    font-weight: bold;
}

#btnGenerate {
    width: 50%;
    height: 40px;
    background-color: #673AB7;
    border: none;
    border-radius: 7px;
    color: #fff;
    text-transform: uppercase;
  outline: none;
}
#btnGenerate:hover{
    background-color: #512DA8;
}

.container > section > form > #generate { padding: 10px; } 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript.

Let's break down the code step by step:

1. Four variables are declared to store references to different HTML elements using their IDs:

  • txtNumber: This represents an input field where the user can input a number.
  • txtInterval: This represents another input field where the user can input an interval.
  • btnGenerate: This is a button element that the user can click to trigger the generation of calculations.
  • ans: This represents an HTML element where the calculated results will be displayed.

2. An event listener is added to the document object, listening for the 'DOMContentLoaded' event. When this event fires (when the page finishes loading), the onFocus function will be called. This function ensures that the focus is set on the txtNumber input field when the page loads.

3. An event listener is added to the btnGenerate button element, listening for the 'click' event. When the button is clicked, the onClick function will be executed.

4. Two event listeners are added to the txtInterval and txtNumber input fields, both listening for the 'keydown' event. This event is triggered when a key is pressed down. The onKeyDown function is called when this event occurs. In this case, if the pressed key is the letter 'e', the event's default behavior (e.g., typing the letter 'e') is prevented.

5. The onClick function is defined. It performs the following steps:

  • Initializes a variable count to keep track of the multiplication iterations.
  • Calls the validateNumber function with the value from the txtNumber input field. If the number is not valid (empty), it proceeds with the calculations.
  • In a loop, it multiplies the value entered in txtNumber by the current count and displays the calculation result in the ans element.
  • Increments the count for the next iteration.
  • Calls the validateInterval function with the value from the txtInterval input field.

6. The validateNumber function is defined to validate the input number. It checks if the number is empty and sets ret (return value) accordingly. If the number is not empty and the ans element is not empty, it clears the ans element. The function returns the value of ret.

7. The validateInterval function is defined to validate the input interval. It checks if the interval is greater than 100. If it is, it clears the ans element and sets ret to true. The function returns the value of ret.

8. The onKeyDown function is defined to prevent the default behavior of the 'e' key, effectively disabling the input of the letter 'e' in the input fields.

9. The onFocus function is defined to set the focus on the txtNumber input field when the page loads.

Create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document, so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

var txtNumber = document.getElementById('txtNumber');
var txtInterval = document.getElementById('txtInterval');
var btnGenerate = document.getElementById('btnGenerate');
var ans = document.getElementById('ans');

document.addEventListener('DOMContentLoaded', onFocus);
btnGenerate.addEventListener('click', onClick);
txtInterval.addEventListener('keydown', onKeyDown);
txtNumber.addEventListener('keydown', onKeyDown);
 
function onClick() {
    let count = 0;
    if (!validateNumber(txtNumber.value)) {
        while (count <= txtInterval.value) {
            ans.innerHTML += parseFloat(txtNumber.value) + ' X ' + count + ' = ' + (parseFloat(txtNumber.value) * count) + '<br>';
            count++;
        }
        validateInterval(txtInterval.value);
    }
    return count;
}

function validateNumber(number) {
    let ret = false;
    if (number == '') ret = true;
    else if (number != '' && ans != '') ans.innerHTML = '';
    return ret;
}

function validateInterval(interval) {
    let ret = false;
    if (interval > 100) {
        ans.innerHTML = '';
        ret = true;
    }
    return ret;
}

function onKeyDown(e) {
    if (e.key === 'e') e.preventDefault();
}

function onFocus() {
    txtNumber.focus();
}

Final Output:

Build Your Own Multiplication Table Generator using HTML, CSS, and JavaScript.gif

Conclusion:

In conclusion, the journey to create a Multiplication Table Generator using HTML, CSS, and JavaScript has been a rewarding exploration of the possibilities that lie within web development. Through this project, we've harnessed the capabilities of each technology to craft a practical and user-friendly tool.

From setting up the basic HTML structure to styling our generator with CSS, and finally implementing the dynamic logic with JavaScript, we've seen how these three components seamlessly integrate to deliver an interactive user experience. This tutorial has not only equipped you with the technical skills to build a multiplication table generator but has also provided a glimpse into the creative and problem-solving aspects of web development.

As you reflect on your journey, remember that web development is a constantly evolving field. The concepts and techniques you've learned here are stepping stones to even greater possibilities. You now have the foundation to explore more complex projects, experiment with new ideas, and contribute to the ever-growing landscape of the digital world.

The Multiplication Table Generator is just one example of how web technologies can enhance everyday tasks and make information more accessible. As you continue your coding journey, consider how you can apply similar principles to address other challenges and create innovative solutions.

In a world where technology plays an increasingly significant role, your newfound skills can have a profound impact. So, whether you're a student seeking to simplify your studies or a developer looking to expand your repertoire, take pride in your accomplishments. The Multiplication Table Generator you've created is not just a tool – it's a testament to your dedication and ability to bring ideas to life through code.

As you move forward, remember that the skills you've acquired are not just about lines of code; they're about the potential to shape the digital world and make a difference. So, embrace the journey, keep learning, and continue to explore the vast horizons of web development. Congratulations on your success, and may your coding adventures be endless and fulfilling!

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