0

I simply would like a function that allows all contenteditable child elements draggable using jQuery (no external jQuery plugins).

I found this useful piece of code here How do I make an element draggable in jQuery?.

    function draggable(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);
}

This allows draggability on any element by simply typing $('.div').on("mousedown", draggable);

I have also found this useful piece of code here Prevent contenteditable adding <div> on ENTER - Chrome.

    $('div[contenteditable]').keydown(function(e) {
    // catch the enter key being pressed
    if (e.keyCode === 13) {
      $(this).find("*").off("mousedown.drag").on("mousedown.drag", draggable);
    }
  });

i intend on attaching the function to all child elements the contenteditable creates when the user presses enter to make them draggable.

Can anybody help?

Jevon
  • 219
  • 2
  • 12

1 Answers1

1

I recommend using jQuery UI's draggable feature:

  <script>
      $(function() {
          $("div[contenteditable]").draggable();
      });
  </script>

It's very simple and if you want to avoid overloading your page with unused features of jQuery UI, you can deselect components in the jQuery UI download section to reduce it to your needs.

Jonathan
  • 1,367
  • 2
  • 17
  • 43
  • I dont intend on using any external plugins as sais in the question. Your answer also targets the content editable and i intend on targeting any children it conjures after the users press enter. – Jevon Sep 26 '19 at 18:51