1

My .popup divs are draggable, thanks to this jquery function :

$(function()
{
    $('.popup').draggable({
        drag: function(event, ui) {}
    });
});

BUT... Once the page is loaded, I add a .popup div in another div's innerHTML. This div is not draggable. Do you know why ?

Thank you for your help, Stefan

Stefan Dacey
  • 165
  • 12
  • You need to give some more code. – Asim Nov 08 '16 at 20:12
  • Because you are only applying the `.draggable` method upon page load, to the `.popup` elements that exist at that moment. This may help: http://stackoverflow.com/questions/15909041/jquery-how-to-use-live-on-draggable – Scott Marcus Nov 08 '16 at 20:13

1 Answers1

1

BUT... Once the page is loaded, I add a .popup div in another div's innerHTML. This div is not draggable. Do you know why ?

This happens because the new div, even if you added the class popup, has not been initialized to a draggable element.

You may do this like:

$(function () {
  $('#btn').on('click', function(e) {
    $('div.ui-widget-content:not(.popup)').addClass('popup').draggable({
      drag: function(event, ui) {
        console.log('2 drag');
      }
    });
  })
  $('.popup').draggable({
    drag: function(event, ui) {
      console.log('1 drag');
    }
  });
});
.ui-widget-content { width: 100px; height: 100px; padding: 0.5em; display: inline; }
<link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>


<div class="ui-widget-content popup">
    Drag me around
</div>
<div class="ui-widget-content">
    Second Drag me around
</div>
<button type="button" id="btn">Add popup class to second div</button>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61
  • Sooo... if I use your code... the second div works. It's draggable. But if I create another div (with the ui-widget-content, a different id than the previous one), the second div doesn't work anymore. Only the third (and first) one is draggable. – Stefan Dacey Nov 09 '16 at 12:21
  • @StefanDigital If you want to make a div draggable the code is: $('div.ui-widget-content:not(.popup)').addClass('popup').draggable({ The point is: how to address a div? You need to adapt this part: $('div.ui-widget-content:not(.popup)') using the correct selector. For instance, if a div has an id equal to div1 you may write: $('#div1').addClass('popup').draggable({ I hope this will help you. Thanks so much. – gaetanoM Nov 09 '16 at 21:01