https://cdn.statically.io/gh/dte-project/a/1e23173799f8ac7c346f345f20de4e5ccb246b1e/shell.v2.min.css
Loading...

Rabu, 27 Februari 2013

Membuat elemen HTML menjadi bisa digeser-geser ternyata jauh lebih mudah dibandingkan dengan apa yang Saya pikir selama ini. Fungsi di bawah ini murni menggunakan JavaScript biasa dan tidak memerlukan library apapun. Berbeda dengan plugin draggable buatan Saya yang dulu:

HTML

<div id="draggable-element" style="position:relative;">Drag me!</div>

JavaScript

var selected = null, // Object of the element to be moved
x_pos = 0, y_pos = 0, // Stores x & y coordinates of the mouse pointer
x_elem = 0, y_elem = 0; // Stores top, left values (edge) of the element

// Will be called when user starts dragging an element
function _drag_init(elem) {
selected = elem; // Store the object of the element which needs to be moved
x_elem = x_pos - selected.offsetLeft;
y_elem = y_pos - selected.offsetTop;
}

// Will be called when user dragging an element
function _move_elem(e) {
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';
}
}

// Destroy the object when we are done
function _destroy() {
selected = null;
}

// Bind the functions here...
document.getElementById('draggable-element').onmousedown = function() {
_drag_init(this);
return false;
};

document.onmousemove = _move_elem;
document.onmouseup = _destroy;

Demo


Referensi: DigiMantra - Drag an Element, Image, etc… Using JavaScript

View more articles

Keyword link

Subscribe via Email

Sign up by email to get the latest news from us..

Contact us

Send a message to us.

Template Hasil Cloning II | Copyright 2015 - 2016 | Rip Code by Shn | ShannenPio Cloning