O'Reilly logo

Developing Web Components by Jason Strimpel, Jarrod Overson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required