JavaScript Background Color Changer Tutorial For Beginners

JavaScript is a popular programming language for developing interactive web applications. One of the frequently desired features in web projects is the ability to dynamically change the background color of a page. In this tutorial, we will learn how to create a simple "Javascript Background Color Changer" for beginners. In the context of the "Javascript Background Color Changer Tutorial For Beginners" article, the DOM (Document Object Model) plays a crucial role in achieving the dynamic background color changing functionality.

The DOM is a programming interface provided by web browsers that allows JavaScript to access and manipulate the elements of an HTML document. It represents the entire structure of the web page as a tree-like structure, where each element in the HTML document becomes a node in the DOM tree. This enables JavaScript to interact with the HTML elements, modify their content, attributes, and styles, and respond to user actions.

In this tutorial, the author will use HTML, CSS, and JavaScript to implement the feature of changing the background color of the page with an attractive transition effect. Users will be able to easily click the "Change Background" button to see the web page change its color randomly from a predefined list of colors. Let's start the tutorial!

Tutorial

  1. Create a folder named bg-javascript to facilitate our tutorial.
  2. Then, open your IDE.
  3. Create index.html for html file and save into bg-javascript folder.
  4. Here is the HTML code :
  5. <!DOCTYPE html>
    <html>
    <head>
        <title>Change Background With More Colors</title>
        <link rel="stylesheet" href="style.css"> 
    </head>
    
    <body>
        <button type="button">Change Background</button>
        <script src="script.js"></script>
    </body>
    </html>

  6. For CSS file you need to create style.css and save into bg-javascript folder.
  7. CSS code :
  8. /* Styles for the body element */
    body {
        text-align: center; /* Center aligns the text content within the body */
        font-family: Arial, sans-serif; /* Sets the font-family for the text */
        margin: 0; /* Removes margin around the body */
        padding: 0; /* Removes padding around the body */
        height: 100vh; /* Sets the height of the body to 100% of the viewport height */
        display: flex; /* Displays the body content as a flex container */
        align-items: center; /* Centers the content vertically */
        justify-content: center; /* Centers the content horizontally */
        background-color: #3498db; /* Sets the background color to a blue shade */
        transition: background-color 0.5s ease; /* Applies a smooth transition effect for background color changes */
    }
    
    /* Styles for the button element */
    button {
        padding: 10px 20px; /* Adds padding to the button content */
        font-size: 16px; /* Sets the font size of the button text */
        cursor: pointer; /* Changes the cursor to a pointer on hover */
        border: none; /* Removes the button border */
        background-color: #2c3e50; /* Sets the background color of the button to a dark blue shade */
        color: #fff; /* Sets the text color of the button to white */
        border-radius: 5px; /* Adds rounded corners to the button */
        box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.2); /* Adds a subtle shadow effect to the button */
        transition: background-color 0.3s ease, transform 0.2s ease; /* Applies smooth transition effects for background color and transform changes */
    }
    
    /* Styles for the button element when hovered */
    button:hover {
        background-color: #34495e; /* Changes the background color of the button to a darker shade on hover */
        transform: scale(1.1); /* Enlarges the button slightly on hover */
    }
    
    /* CSS Animation keyframes for scaling and fading effect */
    @keyframes scaleAndFade {
        0% {
            transform: scale(1); /* Initial scale value for the animation */
            opacity: 1; /* Initial opacity value for the animation */
        }
        50% {
            transform: scale(1.2); /* Midway scale value for the animation */
            opacity: 0.8; /* Midway opacity value for the animation */
        }
        100% {
            transform: scale(1); /* Final scale value for the animation */
            opacity: 1; /* Final opacity value for the animation */
        }
    }
    
    /* Class for applying the scaling and fading animation */
    .change-background-animation {
        animation: scaleAndFade 0.5s ease; /* Applies the defined keyframe animation with a 0.5s duration and ease timing function */
    }

  9. Result when the author open index.html file in bg-javascript folder :
  10. And last create script.js for javascript file and save it in the folder mentioned earlier.
  11. Javascript code :
  12. const btn = document.getElementsByTagName('button')[0];
    const colors = [
        '#3498db', '#e74c3c', '#1abc9c', '#f39c12', '#9b59b6',
        '#2ecc71', '#f1c40f', '#e67e22', '#95a5a6', '#34495e',
        '#7f8c8d', '#d35400', '#c0392b', '#16a085', '#8e44ad',
        '#27ae60', '#d35400', '#2980b9', '#f39c12', '#bdc3c7'
    ];
    
    btn.addEventListener('click', function() {
        const randomColor = colors[Math.floor(Math.random() * colors.length)];
        document.body.style.backgroundColor = randomColor;
        document.body.classList.add('change-background-animation');
    
        setTimeout(() => {
            document.body.classList.remove('change-background-animation');
        }, 500);
    });

    Here's the step-by-step explanation of the JavaScript code:

    Get a reference to the button element:
    const btn = document.getElementsByTagName('button')[0];

    - The code above retrieves the first button element in the page (if there is any) and stores it in the variable btn.

    Define a list of colors:
    const colors = [
        '#3498db', '#e74c3c', '#1abc9c', '#f39c12', '#9b59b6',
        '#2ecc71', '#f1c40f', '#e67e22', '#95a5a6', '#34495e',
        '#7f8c8d', '#d35400', '#c0392b', '#16a085', '#8e44ad',
        '#27ae60', '#d35400', '#2980b9', '#f39c12', '#bdc3c7'
    ];

    - The code above defines an array colors containing a set of hexadecimal color codes.

    Add an event listener to the button:
    btn.addEventListener('click', function() {
        // The action code will be placed here
    });

    - The code above adds an event listener to the button (btn) that will respond when the button is clicked. When the button is clicked, the function inside addEventListener will be executed.

    Get a random color from the list of colors:
    const randomColor = colors[Math.floor(Math.random() * colors.length)];

    - The code above retrieves a random color from the colors array by using Math.random() to generate a random value between 0 and 1, then multiplying it by the length of the colors array and rounding it down to the nearest integer using Math.floor(). As a result, we get a valid random index for an element in the colors array.

    Change the background color of the page:
    document.body.style.backgroundColor = randomColor;

    - The code above changes the background color (backgroundColor) of the body element (the page) with the random color value obtained earlier.

    Add an animation class:
    document.body.classList.add('change-background-animation');

    - The code above adds the CSS class named change-background-animation to the body element. As a result, the element will experience a certain animation when changing its background.

    Remove the animation class after a certain time:
    setTimeout(() => {
        document.body.classList.remove('change-background-animation');
    }, 500);

    - The code above uses the setTimeout function to remove the change-background-animation class from the body element after 500 milliseconds (half a second). This is done to create a repeating animation effect.

    So, when the button is clicked, the page's background color will change randomly, followed by a transition animation. After half a second, the animation will be removed, and the page will return to normal.

  13. Result :
  14. Demo live https://galihap76.github.io/javascript-background-color-changer.github.io/.
  15. Done.

Closing

Thus, we have successfully created a simple yet captivating "Javascript Background Color Changer" for beginners. In this tutorial, we utilized HTML, CSS, and JavaScript to provide an interactive experience for users, enabling them to easily change the background color of the web page with appealing colors. Best of luck with your endeavors, and keep nurturing creativity and expertise in the world of programming!