Aesthetic Cookie
Aesthetic Cookie

Reputation: 49

Make only part of a div draggable

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. =)

Upvotes: 3

Views: 2163

Answers (3)

Bless Yahu
Bless Yahu

Reputation: 1341

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).

Upvotes: 0

Daniel Arechiga
Daniel Arechiga

Reputation: 967

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);
}

Upvotes: 0

Max Kroshka
Max Kroshka

Reputation: 487

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);
}

Upvotes: 3

Related Questions