Skip to content
Advertisement

Use a child element to drag a parent element

I want to make something like navigation bar that can move whole element, without allowing dragging anywhere on the parent entire element to control the dragging. For example:

<div class="undraggable">
    <div class="draggable"></div>
    content
</div>

Dragging on a title bar drags the whole window that it is contained within, but dragging elsewhere on the window container does not drag the window.

I tried to use dragresize but I can’t make only draggable (don’t want resizable) object with his code.

Advertisement

Answer

  1. Register your mousedown handler on the drag controller (e.g. the title bar of the window).
  2. When you are dragging, update the position of a different element (e.g. the window wrapper).

I have an example of this here:
http://phrogz.net/js/PhrogzWerkz/WerkWin.html

If you need this to work with a specific library—like a jQuery UI library—then please edit your question to say say.

Simpler Demo: http://jsfiddle.net/VCQuN/1/

<div class="window">
  <div class="titlebar">Hello, World!</div>
  <div class="content">
    <p>Window <b>Content!</b></p>
  </div>
</div>​
// For each item with a `window` class…
var windows = document.querySelectorAll('.window');
[].forEach.call(windows,function(win){

  // …find the title bar inside it and do something onmousedown
  var title = win.querySelector('.titlebar');
  title.addEventListener('mousedown',function(evt){

    // Record where the window started
    var real = window.getComputedStyle(win),
        winX = parseFloat(real.left),
        winY = parseFloat(real.top);

    // Record where the mouse started
    var mX = evt.clientX,
        mY = evt.clientY;

    // When moving anywhere on the page, drag the window
    // …until the mouse button comes up
    document.body.addEventListener('mousemove',drag,false);
    document.body.addEventListener('mouseup',function(){
      document.body.removeEventListener('mousemove',drag,false);
    },false);

    // Every time the mouse moves, we do the following 
    function drag(evt){
      // Add difference between where the mouse is now
      // versus where it was last to the original positions
      win.style.left = winX + evt.clientX-mX + 'px';
      win.style.top  = winY + evt.clientY-mY + 'px';
    };
  },false);
});
​
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement