Skip to Content
Developing Web Components
book

Developing Web Components

by Jarrod Overson, Jason Strimpel
February 2015
Intermediate to advanced
252 pages
5h 17m
English
O'Reilly Media, Inc.
Content preview from Developing Web Components

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Getting Started with Web Components

Getting Started with Web Components

Prateek Jadhwani
Grid Layout in CSS

Grid Layout in CSS

Eric A. Meyer
Pure JavaScript

Pure JavaScript

Allen R. Wyke, Jason Gilliam, Charlton Ting

Publisher Resources

ISBN: 9781491905685Errata PageSupplemental Content