Jon Snow's papa Jon Snow's papa - 4 months ago 7
jQuery Question

Jquery calling function to parent element

I have got this html

<div class='Aname'>
<div class='cllt'>
<img src='../img/close.png' class='cl' />
<div class='drag'>
<img src='../img/dr.png' class='dr' /></div>
</div>
</div>


And this jquery function

function handle_mousedown(e){
window.my_dragging = {};
my_dragging.pageX0 = e.pageX;
my_dragging.pageY0 = e.pageY;
my_dragging.elem = this;
my_dragging.offset0 = $(this).offset();
function handle_dragging(e){
var left = my_dragging.offset0.left + (e.pageX - my_dragging.pageX0);
var top = my_dragging.offset0.top + (e.pageY - my_dragging.pageY0);
$(my_dragging.elem)
.offset({top: top, left: left});
}
function handle_mouseup(e){
$('body')
.off('mousemove', handle_dragging)
.off('mouseup', handle_mouseup);
}
$('body')
.on('mouseup', handle_mouseup)
.on('mousemove', handle_dragging);
}


source How do I make an element draggable in jQuery?;
And i have tried this way

$('.dr').mousedown(function(){
$(this).parent().parent().parent(handle_mousedown)
});


But it is not dragging it

Answer

Give your function a second argument that indicates the element that should be dragged instead of this.

function handle_mousedown(e, elem) {
  var my_dragging = {};
  my_dragging.pageX0 = e.pageX;
  my_dragging.pageY0 = e.pageY;
  my_dragging.elem = elem;
  my_dragging.offset0 = elem.offset();

  function handle_dragging(e) {
    var left = my_dragging.offset0.left + (e.pageX - my_dragging.pageX0);
    var top = my_dragging.offset0.top + (e.pageY - my_dragging.pageY0);
    my_dragging.elem
      .offset({
        top: top,
        left: left
      });
  }

  function handle_mouseup(e) {
    $('body')
      .off('mousemove', handle_dragging)
      .off('mouseup', handle_mouseup);
  }
  $('body')
    .on('mouseup', handle_mouseup)
    .on('mousemove', handle_dragging);
}

$('.dr').mousedown(function(e) {
  handle_mousedown(e, $(this).parent().parent().parent());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='Aname'>
    <div class='cllt'>
      <img src='../img/close.png' class='cl' />
      <div class='drag'>
        <img src='../img/dr.png' class='dr' /></div>
    </div>
</div>

Comments