Reputation: 9830
I have a fixed div
which I made draggable through JQuery UI
. The div
is centered on startup.
The problem is, when the div
gets dragged off screen, (meaning, because it goes off screen, the page starts scrolling,) the div
goes way over to the side. The more you drag, the more it goes away from the cursor.
Also, how can I position the div
with percentage, this way when the browser gets resized, the div
will maintain its position? (Even after it gets dragged.)
var dragDiv = $('#draggable');
dragDiv.css({
'top': ($(window).height() / 2) - (dragDiv.outerHeight() / 2),
'left': ($(window).width() / 2) - (dragDiv.outerWidth() / 2)
});
dragDiv.draggable();
body {
width: 2000px;
height: 2000px;
background-image: url("http://www.freevector.com/site_media/preview_images/FreeVector-Square-Patterns-Set.jpg");
}
#draggable {
color: lightblue;
background-color: red;
width: 200px;
position: fixed;
}
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.4.js"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<div id="draggable">Drag Me!</div>
Upvotes: 0
Views: 1531
Reputation: 16170
A simple solution would be to use a fixed position overlay/wrapper:
var dragDiv = $('#draggable');
dragDiv.css({
'top': ($(window).height() / 2) - (dragDiv.outerHeight() / 2),
'left': ($(window).width() / 2) - (dragDiv.outerWidth() / 2)
});
dragDiv.draggable({
containment: "parent" // <- keep draggable within fixed overlay
});
body {
width: 2000px;
height: 2000px;
background-image: url("http://www.freevector.com/site_media/preview_images/FreeVector-Square-Patterns-Set.jpg");
}
#fixed {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: rgba(0, 0, 0, 0.25)
}
#draggable {
color: lightblue;
background-color: red;
width: 200px;
position: absolute;
}
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.4.js"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<div id="fixed">fixed overlay<!-- add fixed position overlay/wrapper -->
<div id="draggable">Drag Me!</div>
</div>
As for setting the position in percent, you can check this answer.
Upvotes: 1