If you want to drag your element from one point to another, here is the code below using Javascript:
HTML:
<div id="dragElement">Drag me!</div>
CSS:
#dragElement {
width:100px;
height:100px;
background-color:#666;
color:white;
padding:10px 12px;
cursor:move;
top:0;
left:0;
position:absolute; /* we can make it relative, fixed also but not static. */
}
JS:
var selected = null, // Moving element
x_pos = 0, y_pos = 0, //saving the x-axis and y-axis coordinates of the mouse pointer
x_elem = 0, y_elem = 0; // saving top, left values of the element
function _drag_init(elem) { // when user start dragging, this function is called
selected = elem;
x_elem = x_pos - selected.offsetLeft;
y_elem = y_pos - selected.offsetTop;
}
function _move_elem(e) { // when the user is dragging, this function is called
x_pos = document.all ? window.event.clientX : e.pageX;
y_pos = document.all ? window.event.clientY : e.pageY;
if (selected !== null) {
selected.style.left = (x_pos - x_elem) + 'px';
selected.style.top = (y_pos - y_elem) + 'px';
}
}
function _destroy() { // when the user is done with dragging, this function is called
selected = null;
}
// Bind the functions...
document.getElementById('"dragElement').onmousedown = function () {
_drag_init(this);
return false;
};
document.onmousemove = _move_elem;
document.onmouseup = _destroy;
Hope this will help you with dragging.
0 Comment(s)