Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 1060174 of User input and controls

  • Revision slug: Web/Apps/Fundamentals/User_input_methods
  • Revision title: User input and controls
  • Revision id: 1060174
  • Created:
  • Creator: KadirTopal
  • Is current revision? Yes
  • Comment Revert to revision of 2016-02-29 03:32:17 by chrisdavidmills: "spam"

Revision Content

Modern web user input goes beyond simple mouse and keyboard: think of touchscreens for example. This article provides recommendations for managing user input and implementing controls in open web apps, along with FAQs, real-world examples, and links to further information for anyone needing more detailed information on the underlying technologies. Relevant APIs and events include touch events, Pointer Lock API, Screen Orientation API, Fullscreen API, Drag & Drop and more.

User input and controls workflow

The following diagram illustrates the typical workflow for implementing user input mechanisms:

First of all, you need to decide which input mechanisms you want to cover in your application out of mouse, keyboard, finger touch and so on. Once you decided the input mechanisms, you can control them using tools offered by the web platform or JavaScript libraries.

Recommendations

Available input mechanisms depend on the capabilities of the device running the application:

  • Some devices provide touchscreen displays: the Web Platform offers touch events to interpret finger activity on touch-based user interfaces.
  • For devices providing a mouse/touchpad as a pointing method, the Pointer Lock API helps you in implementing a first person 3D game or other applications requiring full control of the pointing device. And the Fullscreen API helps you in displaying your app in fullscreen mode.
  • Using features such as contentEditable elements you can implement fast rich-text editors and with Drag&Drop let users moving elements inside your app. When screen orientation matters for your application, through the Screen Orientation API you can read the screen orientation state and perform other actions.
  • You should always be mindful of keyboard accessibility where appropriate — many web users only use keyboard to navigate web sites and apps, and locking them out of your functionality is a bad idea.

The following is a set of recommendations and best practices for using such tools in Open Web Apps.

Decide what input mechanism you’re using

Keyboard

Keyboard input can be controlled by your app. For example if you want to add controls when any key gets pressed, you need to add an event listener on the window object:

window.addEventListener("keydown", handleKeyDown, true);
window.addEventListener("keyup", handleKeyUp, true);

where handleKeyDown and handleKeyUp are the functions implementing the controls about the keydown and keyup events.

Note: Have a look at the Events reference and {{domxref("KeyboardEvent")}} guide to find out more about keyboard events.

Mouse

The events occurring when the user interacts with a pointing device such as a mouse are represented by the {{domxref("MouseEvent")}} DOM Interface. Common mouse events include click, dblclick, mouseup, and mousedown. The list of all events using the Mouse Event Interface is provided in the Events reference.

When the input device is a mouse, you can also control user input through the Pointer Lock API and implement Drag & Drop (see below).

Finger touch

When developing web applications meant to be installed on touchscreen devices, it’s a good practice to take into consideration the different capabilities in terms of screen resolution and user input. Touch events can help you implement interactive elements and common interaction gestures on touchscreen devices.

If you want to use touch events, you need to add event listeners and specify handler functions, which will be called when the event gets fired:

element.addEventListener("touchstart", handleStart, false);

element.addEventListener("touchend", handleEnd, false);

element.addEventListener("touchcancel", handleCancel, false);

element.addEventListener("touchleave", handleEnd, false);

element.addEventListener("touchmove", handleMove, false);

where element is the DOM element you want to register the touch events on.

Note: For further information about what you can do with touch events, please read our touch events guide.

Pointer Events

When dealing with devices that incorporate multiple forms of input, like mouse, finger touch and pen input, it might be hard to develop a solution that works for all these different control mechanisms. Pointer Events help developers more easily manage events across devices by normalizing the handling of each one. A pointer can be any point of contact on the screen made by a mouse cursor, pen, touch (including multi-touch), or other pointing input device. The events for handling generic pointer input look a lot like those for mouse: pointerdown, pointermove, pointerup, pointerover, pointerout, etc.

Note: Pointer Events are not widely supported yet, but a pointer.js polyfill is available on Mozilla Github.

Implement controls

Pointer lock

In some cases, typically game development, you might need to access mouse events even when the cursor goes past the boundary of the browser or screen: the {{domxref("Pointer_Lock_API")}} gives you full control of the pointing device.

This is the code to request pointer lock on an element:

element.requestPointerLock();

Note: For a full tutorial and reference, read our {{domxref("Pointer_Lock_API")}} page.

Screen Orientation

When screen orientation matters for your application, you can read the screen orientation state, be informed when this state changes, and able to lock the screen orientation to a specific state (usually portrait or landscape) through the Screen Orientation API.

Orientation data can be retrieved through the {{domxref("screen.orientation")}} attribute or through the orientation media feature. When screen.orientation changes, the {{domxref("screen.orientationchange")}} event is fired on the screen object. Locking the screen orientation is made possible by invoking the {{domxref("screen.lockOrientation")}} method, while the {{domxref("screen.unlockOrientation")}} method removes all the previous screen locks that have been set.

Note: More information about the Screen Orientation API can be found in Managing screen orientation.

Fullscreen

You might need to present an element of your application (such as a {{ htmlelement("video") }}, for example) in fullscreen mode. You can achieve this by calling {{domxref("Element.requestFullscreen()")}} on that element. Bear in mind that many browsers still implement this with a vendor prefix, so you will probably need to fork your code something like this:

var elem = document.getElementById("myvideo");
if (elem.requestFullscreen) {
  elem.requestFullscreen();
} else if (elem.msRequestFullscreen) {
  elem.msRequestFullscreen();
} else if (elem.mozRequestFullScreen) {
  elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
  elem.webkitRequestFullscreen();
}

Note: To find more out about adding fullscreen functionality your application, read our documentation about using fullscreen mode.

Drag & Drop

Drag & Drop allows your application’s users to click and hold the mouse button down over an element, drag it to another location, and release the mouse button to drop the element there.

Here is an example that allows a section of content to be dragged.

<div draggable="true" ondragstart="event.dataTransfer.setData('text/plain', 'This text may be dragged')">

    This text <strong>may</strong> be dragged.

</div>

in which we:

  • Set the draggable attribute to true on the element that you wish to make draggable
  • Add a listener for the dragstart event and set the drag data within this listener

Note: You can find more information in the MDN Drag & Drop documentation.

contentEditable

In open web apps any DOM element can be made directly editable using the contenteditable attribute.

<div contenteditable="true">

    This text can be edited by the user.
</div>

Note: Compatibility information, examples and other resources can be found in the Content Editable guide.

Examples

Tracking multiple touch points at a time
This example tracks multiple touch points at a time, allowing the user to draw in a {{htmlelement("canvas")}} with more than one finger at a time. It will only work on a browser that supports touch events.
Simple pointer lock demo
We've written a simple pointer lock demo to show you how to use it to set up a simple control system. The demo uses JavaScript to draw a ball inside a {{htmlelement("canvas")}} element. When you click the canvas, pointer lock is then used to remove the mouse pointer and allow you to move the ball directly using the mouse.
contentEditable demo
This is a working example showing how contenteditable can be used to create an editable document section, the state of which is then saved using LocalStorage.

Tutorials

Reference

Revision Source

<div class="summary">
<p><span class="seoSummary">Modern web user input goes beyond simple mouse and keyboard: think of touchscreens for example. This article provides recommendations for managing user input and implementing controls in open web apps, along with FAQs, real-world examples, and links to further information for anyone needing more detailed information on the underlying technologies. Relevant APIs and events include <a href="/en-US/docs/Web/Guide/Events/Touch_events">touch events</a>, <a href="/en-US/docs/Web/API/Pointer_Lock_API">Pointer Lock API</a>, <a href="/en-US/docs/Web/API/CSS_Object_Model/Managing_screen_orientation">Screen Orientation API</a>, <a href="/en-US/docs/Web/Guide/API/DOM/Using_full_screen_mode">Fullscreen API</a>, <a href="/en-US/docs/Web/Guide/HTML/Drag_and_drop">Drag &amp; Drop</a> and more.</span></p>
</div>

<h2 id="User_input_and_controls_workflow">User input and controls workflow</h2>

<p>The following diagram illustrates the typical workflow for implementing user input mechanisms:</p>

<p style="text-align: center;"><img alt="" src="https://mdn.mozillademos.org/files/8085/user-input-and-controls.png" style="height:86px; width:303px" /></p>

<p>First of all, you need to decide which input mechanisms you want to cover in your application out of mouse, keyboard, finger touch and so on. Once you decided the input mechanisms, you can control them using tools offered by the web platform or JavaScript libraries.</p>

<h2 id="Recommendations">Recommendations</h2>

<p>Available input mechanisms depend on the capabilities of the device running the application:</p>

<ul>
 <li>Some devices provide touchscreen displays: the Web Platform offers <a href="/en-US/docs/Web/Guide/Events/Touch_events">touch events</a> to interpret finger activity on touch-based user interfaces.</li>
 <li>For devices providing a mouse/touchpad as a pointing method, the <a href="/en-US/docs/Web/API/Pointer_Lock_API">Pointer Lock API</a> helps you in implementing a first person 3D game or other applications requiring full control of the pointing device. And the <a href="/en-US/docs/Web/API/Fullscreen_API">Fullscreen API</a> helps you in displaying your app in fullscreen mode.</li>
 <li>Using features such as <a href="/en-US/docs/Web/Guide/HTML/Content_Editable">contentEditable</a> elements you can implement fast rich-text editors and with <a href="/en-US/docs/Web/Guide/HTML/Drag_and_drop">Drag&amp;Drop</a> let users moving elements inside your app. When screen orientation matters for your application, through the <a href="/en-US/docs/Web/API/CSS_Object_Model/Managing_screen_orientation">Screen Orientation API</a> you can read the screen orientation state and perform other actions.</li>
 <li>You should always be mindful of keyboard accessibility where appropriate — many web users only use keyboard to navigate web sites and apps, and locking them out of your functionality is a bad idea.</li>
</ul>

<p>The following is a set of recommendations and best practices for using such tools in Open Web Apps.</p>

<h3 id="Decide_what_input_mechanism_you’re_using">Decide what input mechanism you’re using</h3>

<h4 id="Keyboard">Keyboard</h4>

<p>Keyboard input can be controlled by your app. For example if you want to add controls when any key gets pressed, you need to add an event listener on the window object:</p>

<pre class="brush: js">
window.addEventListener("keydown", handleKeyDown, true);
window.addEventListener("keyup", handleKeyUp, true);</pre>

<p>where <code>handleKeyDown</code> and <code>handleKeyUp</code> are the functions implementing the controls about the <code>keydown</code> and <code>keyup</code> events.</p>

<div class="note">
<p><strong>Note</strong>: Have a look at the <a href="/en-US/docs/Web/Reference/Events">Events reference</a> and {{domxref("KeyboardEvent")}} guide to find out more about keyboard events.</p>
</div>

<h4 id="Mouse">Mouse</h4>

<p>The events occurring when the user interacts with a pointing device such as a mouse are represented by the {{domxref("MouseEvent")}} DOM Interface. Common mouse events include <a href="/en-US/docs/Web/Reference/Events/click"><code>click</code></a>, <a href="/en-US/docs/Web/Reference/Events/dblclick"><code>dblclick</code></a>, <a href="/en-US/docs/Web/Reference/Events/mouseup"><code>mouseup</code></a>, and <a href="/en-US/docs/Web/Reference/Events/mousedown"><code>mousedown</code></a>. The list of all events using the Mouse Event Interface is provided in the <a href="/en-US/docs/Web/Reference/Events">Events reference</a>.<br />
 <br />
 When the input device is a mouse, you can also control user input through the Pointer Lock API and implement Drag &amp; Drop (see below).</p>

<h4 id="Finger_touch">Finger touch</h4>

<p>When developing web applications meant to be installed on touchscreen devices, it’s a good practice to take into consideration the different capabilities in terms of screen resolution and user input. <a href="/en-US/docs/Web/Guide/Events/Touch_events">Touch events</a> can help you implement interactive elements and common interaction gestures on touchscreen devices.<br />
 <br />
 If you want to use touch events, you need to add event listeners and specify handler functions, which will be called when the event gets fired:</p>

<pre class="brush: js">
element.addEventListener("touchstart", handleStart, false);

element.addEventListener("touchend", handleEnd, false);

element.addEventListener("touchcancel", handleCancel, false);

element.addEventListener("touchleave", handleEnd, false);

element.addEventListener("touchmove", handleMove, false);</pre>

<p>where <code>element</code> is the DOM element you want to register the touch events on.</p>

<div class="note">
<p><strong>Note</strong>: For further information about what you can do with touch events, please read our <a href="/en-US/docs/Web/Guide/Events/Touch_events">touch events guide</a>.</p>
</div>

<h4 id="Pointer_Events">Pointer Events</h4>

<p>When dealing with devices that incorporate multiple forms of input, like mouse, finger touch and pen input, it might be hard to develop a solution that works for all these different control mechanisms. <a href="https://www.w3.org/TR/pointerevents/">Pointer Events</a> help developers more easily manage events across devices by normalizing the handling of each one. A pointer can be any point of contact on the screen made by a mouse cursor, pen, touch (including multi-touch), or other pointing input device. The events for handling generic pointer input look a lot like those for mouse: <code>pointerdown</code>, <code>pointermove</code>, <code>pointerup</code>, <code>pointerover</code>, <code>pointerout</code>, etc.</p>

<div class="note">
<p><strong>Note</strong>: Pointer Events are not widely supported yet, but a <a href="https://github.com/mozilla/pointer.js">pointer.js polyfill</a> is available on Mozilla Github.</p>
</div>

<h3 id="Implement_controls">Implement controls</h3>

<h4 id="Pointer_lock">Pointer lock</h4>

<p>In some cases, typically game development, you might need to access mouse events even when the cursor goes past the boundary of the browser or screen: the {{domxref("Pointer_Lock_API")}} gives you full control of the pointing device.</p>

<p>This is the code to request pointer lock on an <code>element</code>:</p>

<pre class="brush: js">
element.requestPointerLock();</pre>

<div class="note">
<p><strong>Note</strong>: For a full tutorial and reference, read our {{domxref("Pointer_Lock_API")}} page.</p>
</div>

<h4 id="Screen_Orientation">Screen Orientation</h4>

<p>When screen orientation matters for your application, you can read the screen orientation state, be informed when this state changes, and able to lock the screen orientation to a specific state (usually portrait or landscape) through the <a href="/en-US/docs/Web/API/CSS_Object_Model/Managing_screen_orientation">Screen Orientation API</a>.</p>

<p>Orientation data can be retrieved through the {{domxref("screen.orientation")}} attribute or through the <a href="/en-US/docs/Web/Guide/CSS/Media_queries#orientation"><code>orientation</code></a> media feature. When <code>screen.orientation</code> changes, the {{domxref("screen.orientationchange")}} event is fired on the screen object. Locking the screen orientation is made possible by invoking the {{domxref("screen.lockOrientation")}} method, while the {{domxref("screen.unlockOrientation")}} method removes all the previous screen locks that have been set.</p>

<div class="note">
<p><strong>Note</strong>: More information about the Screen Orientation API can be found in <a href="/en-US/docs/Web/API/CSS_Object_Model/Managing_screen_orientation">Managing screen orientation</a>.</p>
</div>

<h4 id="Fullscreen">Fullscreen</h4>

<p>You might need to present an element of your application (such as a {{ htmlelement("video") }}, for example) in fullscreen mode. You can achieve this by calling {{domxref("Element.requestFullscreen()")}} on that element. Bear in mind that many browsers still implement this with a vendor prefix, so you will probably need to fork your code something like this:</p>

<pre class="brush: js  language-js">
<code class="language-js"><span class="keyword token">var</span> elem <span class="operator token">=</span> document<span class="punctuation token">.</span><span class="function token">getElementById<span class="punctuation token">(</span></span><span class="string token">"myvideo"</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="keyword token">if</span> <span class="punctuation token">(</span>elem<span class="punctuation token">.</span>requestFullscreen<span class="punctuation token">)</span> <span class="punctuation token">{</span>
  elem<span class="punctuation token">.</span><span class="function token">requestFullscreen<span class="punctuation token">(</span></span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="punctuation token">}</span> <span class="keyword token">else</span> <span class="keyword token">if</span> <span class="punctuation token">(</span>elem<span class="punctuation token">.</span>msRequestFullscreen<span class="punctuation token">)</span> <span class="punctuation token">{</span>
  elem<span class="punctuation token">.</span><span class="function token">msRequestFullscreen<span class="punctuation token">(</span></span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="punctuation token">}</span> <span class="keyword token">else</span> <span class="keyword token">if</span> <span class="punctuation token">(</span>elem<span class="punctuation token">.</span>mozRequestFullScreen<span class="punctuation token">)</span> <span class="punctuation token">{</span>
  elem<span class="punctuation token">.</span><span class="function token">mozRequestFullScreen<span class="punctuation token">(</span></span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="punctuation token">}</span> <span class="keyword token">else</span> <span class="keyword token">if</span> <span class="punctuation token">(</span>elem<span class="punctuation token">.</span>webkitRequestFullscreen<span class="punctuation token">)</span> <span class="punctuation token">{</span>
  elem<span class="punctuation token">.</span><span class="function token">webkitRequestFullscreen<span class="punctuation token">(</span></span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="punctuation token">}</span></code></pre>

<div class="note">
<p><strong>Note</strong>: To find more out about adding fullscreen functionality your application, read our documentation about <a href="/en-US/docs/Web/Guide/API/DOM/Using_full_screen_mode">using fullscreen mode</a>.</p>
</div>

<h4 id="Drag_Drop">Drag &amp; Drop</h4>

<p><a href="/en-US/docs/Web/Guide/HTML/Drag_and_drop">Drag &amp; Drop</a> allows your application’s users to click and hold the mouse button down over an element, drag it to another location, and release the mouse button to drop the element there.<br />
 <br />
 Here is an example that allows a section of content to be dragged.</p>

<pre class="brush: html">
&lt;div draggable="true" ondragstart="event.dataTransfer.setData('text/plain', 'This text may be dragged')"&gt;

    This text &lt;strong&gt;may&lt;/strong&gt; be dragged.

&lt;/div&gt;</pre>

<p>in which we:</p>

<ul>
 <li>Set the <a href="/en-US/docs/Web/HTML/Global_attributes#draggable"><code>draggable</code></a> attribute to true on the element that you wish to make draggable</li>
 <li>Add a listener for the <a href="/en-US/docs/Web/Events/dragstart"><code>dragstart</code></a> event and set the drag data within this listener</li>
</ul>

<div class="note">
<p><strong>Note</strong>: You can find more information in the <a href="/en-US/docs/Web/Guide/HTML/Drag_and_drop">MDN Drag &amp; Drop documentation</a>.</p>
</div>

<h4 id="contentEditable">contentEditable</h4>

<p>In open web apps any DOM element can be made directly editable using the <a href="/en-US/docs/Web/HTML/Global_attributes#contenteditable"><code>contenteditable</code></a> attribute.</p>

<pre class="brush: html">
&lt;div contenteditable="true"&gt;

    This text can be edited by the user.
&lt;/div&gt;</pre>

<div class="note">
<p><strong>Note</strong>: Compatibility information, examples and other resources can be found in the <a href="/en-US/docs/Web/Guide/HTML/Content_Editable">Content Editable guide</a>.</p>
</div>

<h2 id="Examples">Examples</h2>

<dl>
 <dt><strong><a href="/en/DOM/Touch_events#Example">Tracking multiple touch points at a time</a></strong></dt>
 <dd>This example tracks multiple touch points at a time, allowing the user to draw in a <code>{{htmlelement("canvas")}}</code> with more than one finger at a time. It will only work on a browser that supports touch events.</dd>
 <dt><strong><a href="/en-US/docs/Web/API/Pointer_Lock_API#example">Simple pointer lock demo</a></strong></dt>
 <dd>We've written a simple pointer lock demo to show you how to use it to set up a simple control system. The demo uses JavaScript to draw a ball inside a <code>{{htmlelement("canvas")}}</code> element. When you click the canvas, pointer lock is then used to remove the mouse pointer and allow you to move the ball directly using the mouse.</dd>
 <dt><strong><a href="https://html5demos.com/contenteditable">contentEditable demo</a></strong></dt>
 <dd>This is a working example showing how contenteditable can be used to create an editable document section, the state of which is then saved using <a href="/en-US/docs/Web/Guide/API/DOM/Storage">LocalStorage</a>.</dd>
</dl>

<h2 id="Tutorials">Tutorials</h2>

<ul>
 <li><a href="/en-US/docs/Web/Guide/DOM/Events/Touch_events">Touch events Guide</a></li>
 <li><a href="/en-US/docs/Web/API/CSS_Object_Model/Managing_screen_orientation">Managing screen orientation</a></li>
 <li><a href="/en-US/docs/Web/Guide/API/DOM/Using_full_screen_mode">Using fullscreen mode</a></li>
 <li><a href="/en-US/docs/Web/Guide/HTML/Dragging_and_Dropping_Multiple_Items">Dragging and Dropping Multiple Items</a></li>
 <li><a href="/en-US/docs/Web/Guide/HTML/Drag_operations">Drag Operations Guide</a></li>
</ul>

<h2 id="Reference">Reference</h2>

<ul>
 <li>{{domxref("MouseEvent")}}</li>
 <li>{{domxref("KeyboardEvent")}}</li>
 <li><a href="/en-US/docs/Web/Guide/Events/Touch_events">Touch events</a></li>
 <li>{{domxref("Pointer_Lock_API")}}</li>
 <li><a href="/en-US/docs/Web/API/CSS_Object_Model/Managing_screen_orientation">Screen Orientation API</a></li>
 <li><a href="/en-US/docs/Web/Guide/API/DOM/Using_full_screen_mode">Fullscreen API</a></li>
 <li><a href="/en-US/docs/Web/Guide/HTML/Drag_and_drop">Drag &amp; Drop</a></li>
 <li><a href="/en-US/docs/Web/Guide/HTML/Content_Editable">Content Editable</a></li>
 <li><a href="https://developer.mozilla.org/en-US/Firefox_OS/Platform/Keyboard_events_in_Firefox_OS_TV">Keyboard events in Firefox OS TV</a></li>
 <li><a href="/en-US/docs/Mozilla/Firefox_OS/TVs_connected_devices/TV_remote_control_navigation">Implementing TV remote control navigation</a></li>
</ul>
Revert to this revision