Chapter 7. Making Elements Draggable
Frequently in web applications you will see elements that are draggable—slider handles, dialogs, column resizing handles, etc. If you have ever wondered exactly how this is accomplished, or needed to implement this behavior, then this is the chapter for you! The first step in the process is learning about mouse events.
Note
This and subsequent chapters will utilize jQuery events, which, for the most part, are wrappers to native JavaScript events that are normalized for cross-browser consistency.
Mouse Events
jQuery supports eleven different mouse events. However, making an element draggable only requires understanding three of these events: $.mousemove
, $.mousedown
, and $.mouseup
.
$.mousemove
Tracking mouse movements is fundamental to making an element draggable because the mouse position will be used to coordinate the movement of the element being dragged. The native JavaScript mousemove
event provides the mouse position data, such as the values of clientX
and clientY
, which are properties of the native event object. However, support for these properties varies between browsers. Fortunately, jQuery normalizes these properties as part of the jQuery event object. We bind the $.mousemove
event listener as follows:
$
(
'body'
).
on
(
'mousemove'
,
function
(
e
)
{
// log the normalized mouse coordinates
console
.
log
(
'pageX: '
+
e
.
pageX
+
' '
+
'pageY: '
+
e
.
pageY
);
});
Tip
mousemove
is useful for tracking user mouse movements, which can be used to gather ...
Get Developing Web Components now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.