Home > Net >  Drag event listener on div
Drag event listener on div

Time:09-19

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 image and text will move with the mouse. Is it possible to make the drag event work and the image or link 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>

CodePudding user response:

What you are looking for is Event.preventDefault(). Remove the draggable="false" attribute from your elements and 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")
})

CodePudding user response:

You may use the draggable attribute on the div itself

const div = document.querySelector("div")
div.addEventListener("dragstart", (e) => {
  console.log("it works");
  div.style.border="solid"
})
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 draggable="true">
  <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>

  • Related