DEV Community

Cover image for Dynamically Add/Remove items from list using Javascript
Ahmad Alinaghian
Ahmad Alinaghian

Posted on

Dynamically Add/Remove items from list using Javascript

Random Color Generator

Create a color generator webpage. The page should generate a certain number of random color.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=S, initial-scale=1.0">
    <title>Random Color Generator</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
</head>

<body onload="init()">



    <div class="container" style="width:90vw ; height: 100vh;">
        <div class="colors row "></div>
        <input type="number" name="addColor" placeholder="Enter Number of color you want!">
        <input type="submit" value="+ Add Colors" class="bg-success text-white">
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="index.js"></script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

const container = document.querySelector('.colors'); //select the colors div
const input = document.querySelector('input[type=number]'); //select the input element's value
const addColor = document.querySelector('input[type=submit]'); //select the submit element


function randomColor() { //generate the random color
    let letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

addColor.addEventListener('click', (e) => {
    e.preventDefault();

    for (let i = 0; i < input.value; i++) {
        let color = randomColor();

        container.insertAdjacentHTML('afterbegin',
            `<div class="colorBox d-flex justify-content-center align-items-center m-3 position-relative" style="width:10rem ; height: 7rem; background-color:${color}"> ${color}--${i}<button type="button" class="btn-close position-absolute end-0 top-0 p-2" aria-label="Close" id='remove_${i}'></button></div>`
        )


        document.querySelector('#remove_' + i).addEventListener('click', (e) => {
            let removeElement = e.target.parentNode;      // let removeElement = document.querySelector('#remove_' + i).parentNode;
            container.removeChild(removeElement);
        })
    }

});

Enter fullscreen mode Exit fullscreen mode

Top comments (0)