Question

Is there anyway to define a drag event in MooTools using the mousedown, mouseup and mousemove events. I would like to be able to do something like the following:

$('#knob').addEvent('drag', function (e) {
    // Drag event code goes here...
});
Was it helpful?

Solution

Dragging

Although Mootools has implemented all you need for drag, drop, slide and similar effects, writing your own event is a good way to learn how events work. Here is an example of how to add additional custom event by using the Element.Events Object.

Effect starts on mousedown event that registers mousemove event. When dragging is over mouseup event is fired that removes the mousemove event listener.

Since it can happen that mouse leaves the box (mouseup is not fired to clean up), mouseout event is added also.

At every step of the effect, drag event handler is launched with the original event object passed as argument, You can see the type of the original event with console.log( e.type );

window.addEvent( 'domready', function() {;

    Element.Events.drag = {

        // the function that will get fired when the custom event is added
        onAdd: function() {

            this.addEvents({
                mousedown: function(e) {
                    this.store( 'x', e.page.x - this.getPosition().x );
                    this.store( 'y', e.page.y - this.getPosition().y );

                    this.addEvents({ 
                        mousemove: function(e) {            
                            this.setPosition({
                                x: e.page.x - this.retrieve( 'x' ), 
                                y: e.page.y - this.retrieve( 'y' )
                            });

                            this.fireEvent( 'drag', e );
                        },
                        mouseout: function(e) {
                            this.fireEvent( 'mouseup', e );
                        }
                    });
                },
                mouseup: function(e) {
                    this.removeEvents( 'mousemove' );
                    this.removeEvents( 'mouseout' );
                    this.fireEvent( 'drag', e );
                }

            });
        },

        // the function that will get fired when the custom event is removed
        onRemove: function() {
            this.removeEvents( 'mousedown' );
            this.removeEvents( 'mouseup' );             
        }
    };

    $('draggable').addEvent( 'drag', function( e ) {
        console.log( e.type );
    });


    // $('draggable').removeEvents( 'drag' );

});

A few good articles about Mootools events:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top