imperium2335
imperium2335

Reputation: 24122

Make all bootstrap modals draggable using Jquery UI

I have read a post regarding making Bootstrap's modals draggable which I can do by calling:

$(this).draggable({
    handle: ".modal-header"
});

Where the dialog is created on the page.

The problem is, is that I have many dialogs throughout my system and I want to make them all draggable, without having to find every dialog instance and dropping in that code snippet.

Is there a way to make all dialogs draggable by default?

I have tried:

$('.modal').on('show', function(){
  $(this).draggable({
      handle: ".modal-header"
    });
})

In my global script, but it does nothing.

Upvotes: 0

Views: 5839

Answers (2)

Wasimulator
Wasimulator

Reputation: 11

This worked for me:

$('.modal').draggable({
    handle: ".modal-content"  
});

This will find all html elements with class 'modal' and make them draggable.

I used '.modal-content' instead of 'modal-header' because I don't want users to get stuck if they dragged the modal too far up on the screen. With '.modal-content' they can drag it back from the bottom of the modal.

Please note that you have to use Jquery UI for this to work.

Use document.ready() to ensure all modals are loaded before this code is applied.

If you're using AngularJS like me, and have multiple controllers and views, or not all of your modals are available in the DOM initially, then you can use ng-init on each modal div to call the function that makes them draggable.

HTML:

<div class="modal" ng-init="makeDraggable()">

Javascript:

$rootScope.makeDraggable = function () {
            $('.modal').draggable({
                handle: ".modal-content"
            });
            $('.modal').addClass('click');
        };

Upvotes: 1

MD SHAHIDUL ISLAM
MD SHAHIDUL ISLAM

Reputation: 14523

Try It:

$(document).ready(function() {
    $(".modal").each(function(i) {
        $(this).draggable({
            handle: ".modal-header"  
        });
    });
});

UPDATE

To use draggable plugin to dynamically created element use

(function ($) {
   $.fn.dynamicDraggable = function (opts) {
      this.live("mouseover", function() {
         if (!$(this).data("init")) {
            $(this).data("init", true).draggable(opts);
         }
      });
      return this;
   };
}(jQuery));

And use it as

$(".modal").dynamicDraggable({
     handle: ".modal-header"  
});

Upvotes: 0

Related Questions