wheel

Traducción en curso

El evento "wheel" se dispara cuando la ruleta de un dispositivo (usualmente un ratón) gira. Este evento reemplaza al ahora obsoleto evento mousewheel.

Información general

Interfaz
WheelEvent
Sincronía
asíncrono
Bubble
Si
Cancelable
Si
Target
defaultView, Document, Element
Acción predet.
Scroll, atras/adelante (historial), o zoom.

Propiedades

Este evento cuenta responde a las propiedades  WheelEvent, MouseEvent, UIEventEvent.

Propiedades de WheelEvent

This interface inherits properties from its parents, MouseEvent, UIEvent and Event.

WheelEvent.deltaX Read only
Returns a double representing the horizontal scroll amount.
WheelEvent.deltaY Read only
Returns a double representing the vertical scroll amount.
WheelEvent.deltaZ Read only
Returns a double representing the scroll amount for the z-axis.
WheelEvent.deltaMode Read only
Returns an unsigned long representing the unit of the delta values scroll amount. Permitted values are:
Constant Value Description
DOM_DELTA_PIXEL 0x00 The delta values are specified in pixels.
DOM_DELTA_LINE 0x01 The delta values are specified in lines.
DOM_DELTA_PAGE 0x02 The delta values are specified in pages.

Propiedades de MouseEvent

This interface also inherits properties of its parents, UIEvent and Event.

MouseEvent.altKey Read only
Returns true if the alt key was down when the mouse event was fired.
MouseEvent.button Read only
The button number that was pressed when the mouse event was fired. 
MouseEvent.buttons Read only

The buttons being pressed when the mouse event was fired

MouseEvent.clientX Read only
The X coordinate of the mouse pointer in local (DOM content) coordinates.
MouseEvent.clientY Read only
The Y coordinate of the mouse pointer in local (DOM content) coordinates.
MouseEvent.ctrlKey Read only
Returns true if the control key was down when the mouse event was fired.
MouseEvent.metaKey Read only
Returns true if the meta key was down when the mouse event was fired.
MouseEvent.movementX Read only
The X coordinate of the mouse pointer relative to the position of the last mousemove event.
MouseEvent.movementY Read only
The Y coordinate of the mouse pointer relative to the position of the last mousemove event.
MouseEvent.offsetX Read only
The X coordinate of the mouse pointer relative to the position of the padding edge of the target node.
MouseEvent.offsetY Read only
The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node.
MouseEvent.pageX Read only
The X coordinate of the mouse pointer relative to the whole document.
MouseEvent.pageY Read only
The Y coordinate of the mouse pointer relative to the whole document.
MouseEvent.region Read only
Returns the id of the hit region affected by the event. If no hit region is affected, null is returned.
MouseEvent.relatedTarget Read only

The secondary target for the event, if there is one.

MouseEvent.screenX Read only
The X coordinate of the mouse pointer in global (screen) coordinates.
MouseEvent.screenY Read only
The Y coordinate of the mouse pointer in global (screen) coordinates.
MouseEvent.shiftKey Read only
Returns true if the shift key was down when the mouse event was fired.
MouseEvent.which Read only
The button being pressed when the mouse event was fired.
MouseEvent.mozPressure Read only
The amount of pressure applied to a touch or tablet device when generating the event; this value ranges between 0.0 (minimum pressure) and 1.0 (maximum pressure).
MouseEvent.mozInputSource Read only

The type of device that generated the event (one of the MOZ_SOURCE_* constants listed below). This lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event).

MouseEvent.webkitForce Read only
The amount of pressure applied when clicking
MouseEvent.x Read only
Alias for MouseEvent.clientX.
MouseEvent.y Read only
Alias for MouseEvent.clientY

Propiedades UIEvent

This interface also inherits properties of its parent, Event.

UIEvent.cancelBubble  
Is a Boolean indicating whether the bubbling of the event has been canceled or not.
UIEvent.detailRead only
Returns a long with details about the event, depending on the event type.
UIEvent.isChar Read only
Returns a Boolean indicating whether the event produced a key character or not.
UIEvent.layerX Read only
Returns the horizontal coordinate of the event relative to the current layer.
UIEvent.layerY Read only
Returns the vertical coordinate of the event relative to the current layer.
UIEvent.pageX Read only
Returns the horizontal coordinate of the event relative to the whole document.
UIEvent.pageY Read only
Returns the vertical coordinate of the event relative to the whole document.
UIEvent.sourceCapabilities  Read only
Returns an instance of the InputDeviceCapabilities interface which provides information about the physical device responsible for generating a touch event.
UIEvent.viewRead only
Returns a WindowProxy that contains the view that generated the event.
UIEvent.which Read only  
Returns the numeric keyCode of the key pressed, or the character code (charCode) for an alphanumeric key pressed.

Propiedades Event

Event.bubbles Read only
A boolean indicating whether the event bubbles up through the DOM or not.
Event.cancelBubble
A nonstandard alternative to Event.stopPropagation().
Event.cancelable Read only
A boolean indicating whether the event is cancelable.
Event.currentTarget Read only
A reference to the currently registered target for the event.
Event.deepPath 
Returns an Array of nodes through which the event bubbled.
Event.defaultPrevented Read only
Indicates whether or not event.preventDefault() has been called on the event.
Event.eventPhase Read only
Indicates which phase of the event flow is being processed.
Event.explicitOriginalTarget Read only
The explicit original target of the event (Mozilla-specific).
Event.originalTarget Read only
The original target of the event, before any retargetings (Mozilla-specific).
Event.returnValue
A nonstandard alternative to Event.preventDefault() and Event.defaultPrevented. (old Internet Explorer-specific).
Event.scoped  Read only  
A Boolean indicating whether the given event bubbles. If this value is truedeepPath will only contain a target node.
Event.srcElement
A nonstandard alias for Event.target. (old Internet Explorer-specific)
Event.target Read only
A reference to the target to which the event was originally dispatched.
Event.timeStamp Read only
The time that the event was created.
Event.type Read only
The name of the event (case-insensitive).
Event.isTrusted Read only
Indicates whether or not the event was initiated by the browser (after a user click for instance) or by a script (using an event creation method, like event.initEvent)

Métodos

Este evento implementa métodos de WheelEvent, MouseEvent, UIEventEvent.

Métodos de WheelEvent

This interface doesn't define any methods, but inherits methods from its parents, MouseEvent, UIEvent and Event.

Métodos de MouseEvent

This interface also inherits methods of its parents, UIEvent and Event.

MouseEvent.getModifierState()
Returns the current state of the specified modifier key. See the KeyboardEvent.getModifierState() for details.
MouseEvent.initMouseEvent()
Initializes the value of a MouseEvent created. If the event has already being dispatched, this method does nothing.

Métodos de UIEvent

This interface also inherits methods of its parent, Event.

UIEvent.initUIEvent()
Initializes a UIEvent object. If the event has already being dispatched, this method does nothing.

Métodos de Event

Event.initEvent()
Initializes the value of an Event created. If the event has already being dispatched, this method does nothing.
Event.preventBubble() Obsolete since Gecko 24
Prevents the event from bubbling. Obsolete, use event.stopPropagation instead.
Event.preventCapture() Obsolete since Gecko 24
Obsolete, use event.stopPropagation instead.
Event.preventDefault()
Cancels the event (if it is cancelable).
Event.stopImmediatePropagation()
For this particular event, no other listener will be called. Neither those attached on the same element, nor those attached on elements which will be traversed later (in capture phase, for instance)
Event.stopPropagation()
Stops the propagation of events further along in the DOM.
Event.getPreventDefault()
Non-standard. Returns the value of Event.defaultPrevented. Use Event.defaultPrevented instead.

Especificaciones

Especificación Estado Comentario
Document Object Model (DOM) Level 3 Events Specification
The definition of 'wheel' in that specification.
Working Draft Definición inicial.

Compatibilidad

Característica Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Soporte básico 31 (Yes) 17.0 (17.0) 9.0[1] 18 7.0
Característica Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Soporte básico ? 17.0 (17.0) ? ? ?

[1] Internet Explorer solo toma el evento "wheel" mediante addEventListener, no se permite el atributo onwheel en objetos del DOM. Bug report.
 

Escuchar al evento en distintos navegadores

En el siguiente script se crea el método multi-navegador addWheelListener que permite escuchar el evento wheel en diferentes navegadores a la vez que se previene el funcionamiento por defecto.

// crea el metodo "addWheelListener" global
// ejemplo: addWheelListener( elem, function( e ) { console.log( e.deltaY ); e.preventDefault(); } );
(function(window,document) {

    var prefix = "", _addEventListener, support;

    // detecta el tipo de evento permitido por el navegador
    if ( window.addEventListener ) {
        _addEventListener = "addEventListener";
    } else {
        _addEventListener = "attachEvent";
        prefix = "on";
    }

    // detecta el tipo de evento wheel manejado por el navegador
    support = "onwheel" in document.createElement("div") ? "wheel" : // Los navegadores modernos permiten "wheel"
              document.onmousewheel !== undefined ? "mousewheel" : // Webkit e IE soportan al menos "mousewheel"
              "DOMMouseScroll"; // Asumiremos que el resto de navegadores son Firefox antiguos

    window.addWheelListener = function( elem, callback, useCapture ) {
        _addWheelListener( elem, support, callback, useCapture );

        // controlaremos MozMousePixelScroll en Firefox antiguos
        if( support == "DOMMouseScroll" ) {
            _addWheelListener( elem, "MozMousePixelScroll", callback, useCapture );
        }
    };

    function _addWheelListener( elem, eventName, callback, useCapture ) {
        elem[ _addEventListener ]( prefix + eventName, support == "wheel" ? callback : function( originalEvent ) {
            !originalEvent && ( originalEvent = window.event );

            // Creamos un objeto de evento
            var event = {
                // tomamos como referencia el objeto original
                originalEvent: originalEvent,
                target: originalEvent.target || originalEvent.srcElement,
                type: "wheel",
                deltaMode: originalEvent.type == "MozMousePixelScroll" ? 0 : 1,
                deltaX: 0,
                deltaZ: 0,
                preventDefault: function() {
                    originalEvent.preventDefault ?
                        originalEvent.preventDefault() :
                        originalEvent.returnValue = false;
                }
            };
            
            // calculamos deltaY (y deltaX) dependiendo del evento
            if ( support == "mousewheel" ) {
                event.deltaY = - 1/40 * originalEvent.wheelDelta;
                // Webkit tambien soporta wheelDeltaX
                originalEvent.wheelDeltaX && ( event.deltaX = - 1/40 * originalEvent.wheelDeltaX );
            } else {
                event.deltaY = originalEvent.detail;
            }

            // Disparamos el callback
            return callback( event );

        }, useCapture || false );
    }

})(window,document);

Notas para Gecko

Orden de los eventos en eventos antiguos

Si el evento wheel no ha sido implementado, los eventos DOMMouseScrollMozMousePixelScroll se usarán para dar retrocompativilidad. Sus atributos se calculan dependiendo del delta del evento wheel y el padre más cercano. Si el evento wheel o alguno de los anteriores invoca event.preventDefault(), no ocurrirá nada.

El orden de ejecución del evento es:

  1. Eventos wheel en grupo de eventos por defecto (aplicaciones web y add-ons pueden manejar los eventos de este grupo)
  2. Un evento DOMMouseScroll vertical en caso de que el deltaY, en consecutivas llamadas del evento se vuelva mayor que 1.0 o menor que -1.0
  3. Un evento MozMousePixelScroll vertical en caso de que el deltaY del último evento wheel no sea igual a cero
  4. Un evento DOMMouseScroll horizontal en caso de que el deltaX acumule un valor mayor que 1.0 o menor que -1.0
  5. Un evento MozMousePixelScroll horizontal en caso de que el deltaX del último evento no sea igual que cero
  6. Un evento wheel en el grupo de sistema (Solamente add-ons pueden gestionar este grupo de eventos)


¿Qué ocurre si preventDefault() es llamado?

wheel (grupo por defecto de evetos) Se llama preventDefault()        
DOMMouseScroll (Vertical) No se llama Se llama preventDefault()      
MozMousePixelScroll (Vertical) No se llama defaultPrevented devuelve true Se llama preventDefault()    
DOMMouseScroll (Horizontal) No se llama No se ve afectado No se ve afectado Se llama preventDefault()  
MozMousePixelScroll (Horizontal) No se llama No se ve afectado No se ve afectado defaultPrevented devuelve true Se llama preventDefault()
wheel (grupo de eventos de sistema) defaultPrevented devuelve true defaultPrevented devuelve true defaultPrevented devuelve true defaultPrevented devuelve true defaultPrevented devuelve true

En caso de que un Add-on necesite conocer si uno de los eventos legacy es usado por contenidos del DOM puede usar el evento wheel de #6. Lee la documentación de nsIEventListenerService para mayor detalle acerca del grupo de eventos de sistema.

Los valores delta y las acciones por defecto de eventos predefinidos pueden ser personalizados en las preferencias de usuario (details). Por lo tanto, no se debe presuponer que alguna acción en concreto va a ocurrir tras recibir este evento.

Valores delta

Los valores delta no indican la cantidad de scroll actual de manera predeterminada. Si el usuario presiona alguna tecla mdificadora mientras mueve la rueda de scroll, dicha acción puede causar otra totalmente diferente a la esperada, como ir adelante o atras por el historial o hacer zoom. Además, incluso cuando la acción sea la esperada, el elemento que la recibe puede ser distinto al deseado.
El objetivo del evento wheel solo está definido por la posición del cursor en el momento que se dispara este.

El valor de deltaMode

En Windows, los siguientes 3 eventos nativos del DOM causan eventos wheel.

WM_MOUSEWHEEL (Evento wheel vertical del ratón)
El deltaMode puede ser DOM_DELTA_LINEDOM_DELTA_PAGE. Depende de las preferencias de usuario en Windows (Para configuraciones por defecto, debería ser DOM_DELTA_LINE).
WM_MOUSEHWHEEL (Evento wheel horizontal del ratón)
EldeltaMode puede ser DOM_DELTA_LINEDOM_DELTA_PAGE. Sin embargo, ni la configuración de velocidad de rueda de ratón de Windows ni ningún UI similar de drivers permite modificar el scroll de páginas. De modo que, normalmente este valor es DOM_DELTA_LINE.
WM_GESTURE (Solo utilizado en navegación gestual)
El deltaMode es siempre DOM_DELTA_PIXEL. Pero la mayoría de dispositivos táctiles de portatiles emulan la rueda de ratón en lugar de usar este evento. Este evento es usado típicamente en Tablet PC.

En Mac, el valor de deltaMode depende del dispositivo. Si el dispositivo permite alta resolución, el scroll se hará en pixels, de manera que el valor del deltaMode será DOM_DELTA_PIXEL. De todos modos, el usuario puede cambiarlo a DOM_DELTA_LINE con la preferencia "mousewheel.enable_pixel_scrolling".  Si el dispositivo no soporta alta resolución, es siembre DOM_DELTA_LINE.

En otras plataformas, el valor de deltaMode es siempre DOM_DELTA_LINE.

Eventos no confiables

Los eventos wheel no nativos nunca causarán acción por defecto.

Ver también

Etiquetas y colaboradores del documento

Etiquetas: 
 Colaboradores en esta página: Thargelion, PRDeving
 Última actualización por: Thargelion,