Search code examples
javascriptjqueryhtmlinnerhtml

div in parent's innerHTML not listening to jquery function


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


Solution

  • 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>