Search code examples
jqueryjquery-uidraggable

jQuery draggable DIV with icon


I want to make some draggable DIV's with jQuery' draggable, but those shouldn't be draggable themselve, but only with the help of a little icon on top of each DIV, so that i can only move it, if i click and drag that icon above the DIV instead of dragging whenever I click and drag the the div.

Thanks in advance


Solution

  • Use the handle:

    $( "#draggable" ).draggable({
      handle: "p"
    });
    

    Snippet

    $(function() {
      $( "#draggable" ).draggable({ handle: "p" });
      $( "#draggable2" ).draggable({ cancel: "p.ui-widget-header" });
      $( "div, p" ).disableSelection();
    });
    #draggable, #draggable2 { width: 100px; height: 100px; padding: 0.5em; float: left; margin: 0 10px 10px 0; }
    #draggable p { cursor: move; }
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <link rel="stylesheet" href="https://jqueryui.com/resources/demos/style.css">
    <div id="draggable" class="ui-widget-content">
      <p class="ui-widget-header">I can be dragged only by this handle</p>
    </div>
    
    <div id="draggable2" class="ui-widget-content">
      <p>You can drag me around&hellip;</p>
      <p class="ui-widget-header">&hellip;but you can't drag me by this handle.</p>
    </div>