Drag & Drop

Drag & Drop

THE MODERN WEB

Table of contents

HTML

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

<head>
    <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>Web - Drag and Drop</title>
    <link rel="stylesheet" href="./app.css" />
</head>

<body>
    <section>

        <div class="container">
            <p class="text">Drop Your Items Here</p>
        </div>

        <div class="draggables">
            <p class="draggable_items" draggable="true">1</p>
            <p class="draggable_items" draggable="true">2</p>
            <p class="draggable_items" draggable="true">3</p>
            <p class="draggable_items" draggable="true">4</p>
        </div>

    </section>


    <script src="./index.js"></script>
</body>

</html>

CSS

body {
    font-family: Helvetica;
}

.container {
    border: 2px dotted black;
    height: 200px;
    width: 100%;
}

.container p {
    margin: 60px 0;
    text-align: center;
    font-size: 20px;
}

.draggable_items {
    border: 1px solid black;
    padding: 10px;
    background-color: #2c3e50;
    color: white;
    text-align: center;
    cursor: all-scroll;
}

.draggable_items.dragging {
    background-color: #27ae60;
}
const draggable_items = document.querySelectorAll('.draggable_items');
const container = document.querySelector('.container');
const text = document.querySelector('.text');

draggable_items.forEach(draggable => {
    draggable.addEventListener('dragstart', () => {
        draggable.classList.add('dragging')
    })

    draggable.addEventListener('dragend', () => {
        draggable.classList.remove('dragging')
    })
})

container.addEventListener('dragover', (e) => {
    container.style.height = '100%';
    text.style.display = 'none';
    e.preventDefault()
    const current_draggable_item = document.querySelector('.dragging');
    container.append(current_draggable_item)
})

References

For more reference , you can visit the GitHub repository.