Search code examples
javascripthtmlcssgoogle-chrome-extension

Best way to move/drag DIV around the page?


Having some issues trying to come up with the proper solution to this problem. Right now, I have some functions that after the user right-clicks a context menu, there is a listener that will trigger API fetch and display data inside a div. Currently, the DIV sits on a fixed position bottom right of the page. My goal is for the div to be draggable so the user can move it around as needed and the div does not interfere with the data behind it.

Googling, I found some js frameworks, but I'm not sure how to implement them. Can anyone advise which is the best way to approach this?

This is how the div looks right now. Thank you! current div


Solution

  • You can use Draggable function from jQueryUI library.

    Download the library and make sure you select Draggable checkbox.

    Then, link the library to your html:

    <link rel="stylesheet" href="jquery-ui.min.css">
    <script src="external/jquery/jquery.js"></script>
    <script src="jquery-ui.min.js"></script>
    

    Finally, use draggable in your JavaScript code like this:

    $( "#my_div" ).draggable({
    });
    

    Example:

    $(function(){
      $( "#my_div" ).draggable({
      });
    });
    <!DOCTYPE html>
    <html>
      <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
      </head>
      <body>
        <div id="my_div" style="width:300px;height:300px;border:1px solid black;">
        HELLO<br>
        World<br>
        World<br>
        World<br>
        </div>
      </body>
    </html>