3

How do i create something similar to to jquery's "draggable handles" in Javascript?

(Jquery is unfortunately not an option for me.)

I have div called "dxy" within it I have another div called "draggable_handle". At the moment I can drag dxy around wherever I press. How do I make is so that I can drag dxy around, but only when i press on draggable_handle and no where else in the div?

<div id="dxy">
  <div id="draggable_handle">
    <p>
    Draggable part
    </p>
  </div>
</div>

I made a JsFiddle, which will make what I mean clearer, here: http://jsfiddle.net/Lk2hLthp/7/

Please add some code examples or a jsfiddle as I am a newbie. =)

Aesthetic Cookie
  • 49
  • 1
  • 1
  • 8
  • Does this answer your question? [Drag drop with handle](https://stackoverflow.com/questions/26283661/drag-drop-with-handle) – Emil Dec 18 '20 at 00:17

3 Answers3

3

Add event listeners to inner element instead of outer like this:

function addListeners() {
  document.getElementById('draggable_handle').addEventListener('mousedown', mouseDown, false);
  window.addEventListener('mouseup', mouseUp, false);
}
Max Kroshka
  • 457
  • 2
  • 5
0

I don't know If I understood what you're trying to do but adding the "mousedown" listener to draggable_handle works for me:

document.getElementById('draggable_handle').addEventListener('mousedown', mouseDown, false);
  window.addEventListener('mouseup', mouseUp, false);
}
Daniel Arechiga
  • 847
  • 7
  • 19
0

In your example, merely changing what id you grab in the addListeners function will give you what you need: document.getElementById('draggable_handle').addEventListener('mousedown', mouseDown, false);

instead of: document.getElementById('dxy').addEventListener('mousedown', mouseDown, false);

I forked you fiddle and made the change: http://jsfiddle.net/BlessYAHU/f687ppg8/

This works because in your functions (mouseDown, divMove), you get the container dom element (dxy).

Bless Yahu
  • 1,331
  • 1
  • 12
  • 25