Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Draggable DIV cross-browser (from IE8) with pure JavaScript
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="popup" style="background-color:green;position:absolute;top:0px;left:0px;width:250px;height:250px;z-index:9999;box-shadow: 6px 6px 5px #888888;border-radius:6px;border:1px solid #4f4f4f;">
<div id="popup_bar" style="width:100%;background-color:#aaff66;position:relative;top:0;border-radius:6px 6px 0 0; text-align:center;height:24px;cursor:move">Title</div>
<p>Content of the popup</p>
</div>
</body>
<script>
!function() {
function addListener(element, type, callback, capture) {
if (element.addEventListener) {
element.addEventListener(type, callback, capture);
} else {
element.attachEvent("on" + type, callback);
}
}
function draggable(element) {
var dragging = null;
addListener(element, "mousedown", function(e) {
var e = window.event || e;
dragging = {
mouseX: e.clientX,
mouseY: e.clientY,
startX: parseInt(element.style.left),
startY: parseInt(element.style.top)
};
if (element.setCapture) element.setCapture();
});
addListener(element, "losecapture", function() {
dragging = null;
});
addListener(document, "mouseup", function() {
dragging = null;
if (document.releaseCapture) document.releaseCapture();
}, true);
var dragTarget = element.setCapture ? element : document;
addListener(dragTarget, "mousemove", function(e) {
if (!dragging) return;
var e = window.event || e;
var top = dragging.startY + (e.clientY - dragging.mouseY);
var left = dragging.startX + (e.clientX - dragging.mouseX);
element.style.top = (Math.max(0, top)) + "px";
element.style.left = (Math.max(0, left)) + "px";
}, true);
};
draggable(document.getElementById("popup"));
}();
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.