Home > OS >  How to drag the inner element, not the container?
How to drag the inner element, not the container?

Time:10-17

At times I want to be able to just drag the inner element of a container which also happens to be itself draggable.

Below is an example, you'll see that if you drag the inner element, the 'dragging' class is added to the class list of the container.

<!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>Document</title>
</head>
<body>
    <div id="container" class = "container draggable" draggable = "true"  style = "background-color: rgb(0, 0, 255); width: 500px; height: 500px; left: 50%; top: 50%;">
        <div id="inner" class = "inner draggable" draggable = "true" style = "background-color: red; width: 200px; height: 200px; left: 50%; top: 50%;"></div>
    </div>
</body>
<script>
    //Attach drag event listeners to draggables
    const draggables = document.querySelectorAll('.draggable');
    draggables.forEach(draggable => {
        draggable.addEventListener('dragstart', (e) => {
            draggable.classList.add('dragging');
        })
    
        draggable.addEventListener('dragend', () => {
            draggable.classList.remove('dragging');
        })
    })</script>
</html>

CodePudding user response:

Use Event.stopPropagation to prevent the dragstart event to be propagated from child element to its container:

<!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>Document</title>
</head>
<body>
    <div id="container" class = "container draggable" draggable = "true"  style = "background-color: rgb(0, 0, 255); width: 500px; height: 500px; left: 50%; top: 50%;">
        <div id="inner" class = "inner draggable" draggable = "true" style = "background-color: red; width: 200px; height: 200px; left: 50%; top: 50%;"></div>
    </div>
</body>
<script>
    //Attach drag event listeners to draggables
    const draggables = document.querySelectorAll('.draggable');
    draggables.forEach(draggable => {
        draggable.addEventListener('dragstart', (e) => {
            draggable.classList.add('dragging');
            e.stopPropagation();
        })
    
        draggable.addEventListener('dragend', () => {
            draggable.classList.remove('dragging');
        })
    })</script>
</html>

  • Related