How can use the drag event for a div while the photo and the link inside have dragging: false
attribute?
If we add the draggable: true
attribute to the div, when we drag, the dragged content will move with the mouse.
Is it possible to make the drag event work and the dragged content does not appear on the screen after dragging?
const div = document.querySelector("div")
div.addEventListener("dragstart", (e) => {
console.log("it works")
})
div {
width: 200px;
height: 200px;
position: relative;
overflow: hidden;
}
a {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
color: blue;
font-size: 20px;
text-decoration: none;
}
<div>
<img draggable="false" src="https://4my3boyz.com/content/images/thumbs/0012369_landscape-medley-blue-sky-with-white-clouds-cotton-fabric_500.jpeg">
<a draggable="false" href="#">Blue Sky</a>
</div>
What you are looking for is Event.preventDefault().
Remove the draggable="false"
attribute from your elements, then in your event listener prevent the default behaviour of dragging like this:
const div = document.querySelector("div")
div.addEventListener("dragstart", (e) => {
e.preventDefault()
console.log("it works")
})