Site icon Puneet Sharma – Freelance Web Developer

Pointer and Touch Event Listeners – JavaScript

Pointer Events

The following script can be used for web app supporting pointer events and touch events.

Pointer events are DOM events that are fired for a pointing device. They are designed to create a single DOM event model to handle pointing input devices such as a mouse, pen/stylus or touch (such as one or more fingers).

Touch events are similar to mouse events except they support simultaneous touches and at different locations on the touch surface.


JavaScript

if (window.PointerEvent) {

    north.addEventListener("pointerdown", functionDown, false);
    north.addEventListener("pointerup", functionUp, false);
    north.addEventListener("pointercancel", functionCancel, false);
    north.addEventListener("pointerleave", functionLeave, false);

    south.addEventListener("pointerdown", functionDown, false);
    south.addEventListener("pointerup", functionUp, false);
    south.addEventListener("pointercancel", functionCancel, false);
    south.addEventListener("pointerleave", functionLeave, false);

    east.addEventListener("pointerdown", functionDown, false);
    east.addEventListener("pointerup", functionUp, false);
    east.addEventListener("pointercancel", functionCancel, false);
    east.addEventListener("pointerleave", functionLeave, false);

    west.addEventListener("pointerdown", functionDown, false);
    west.addEventListener("pointerup", functionUp, false);
    west.addEventListener("pointercancel", functionCancel, false);
    west.addEventListener("pointerleave", functionLeave, false);

} else {
    north.addEventListener("mousedown", functionDown, false);
    north.addEventListener("touchstart", functionDown, false);
    north.addEventListener("mouseup", functionLeave, false);
    north.addEventListener("touchend", functionLeave, false);

    south.addEventListener("mousedown", functionDown, false);
    south.addEventListener("touchstart", functionDown, false);
    south.addEventListener("mouseup", functionLeave, false);
    south.addEventListener("touchend", functionLeave, false);

    east.addEventListener("mousedown", functionDown, false);
    east.addEventListener("touchstart", functionDown, false);
    east.addEventListener("mouseup", functionLeave, false);
    east.addEventListener("touchend", functionLeave, false);

    west.addEventListener("mousedown", functionDown, false);
    west.addEventListener("touchstart", functionDown, false);
    west.addEventListener("mouseup", functionLeave, false);
    west.addEventListener("touchend", functionLeave, false);
}
Exit mobile version