File: index.html

package info (click to toggle)
jqapi 1.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: buster, jessie, jessie-kfreebsd, stretch, wheezy
  • size: 3,288 kB
  • ctags: 76
  • sloc: makefile: 12
file content (265 lines) | stat: -rw-r--r-- 22,738 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
<!DOCTYPE html>
<html lang='en'><head><meta http-equiv='content-type' content='text/html; charset=UTF-8' /></head><body>
<div class="entry-content">
        <div class="entry-title roundTop">
          
          <h1 class="jq-clearfix">.on()</h1>
          <div class="entry-meta jq-clearfix">
                        Categories:
            <span class="category"><a href="http://api.jquery.com/category/events/" title="View all posts in Events">Events</a> &gt; <a href="http://api.jquery.com/category/events/event-handler-attachment/" title="View all posts in Event Handler Attachment">Event Handler Attachment</a></span> | <span class="category"><a href="http://api.jquery.com/category/events/" title="View all posts in Events">Events</a></span>
  

          </div>

</div>
<div id="on1" class="entry method">
<h2 class="jq-clearfix roundTop section-title">
<span class="name">.on( events [, selector]  [, data] , handler )</span> <span class="returns">Returns: <a class="return" href="http://api.jquery.com/Types/#jQuery">jQuery</a></span>
</h2>
<div class="jq-box roundBottom entry-details">
<p class="desc"><strong>Description: </strong>Attach an event handler function for one or more events to the selected elements.</p>
<ul class="signatures">
<li class="signature" id="on-events-selector-data-handler">
<h4 class="name">
<span class="versionAdded">version added: <a href="/category/version/1.7/">1.7</a></span>.on( events [, selector] [, data], handler )</h4>
<p class="arguement"><strong>events</strong>One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".</p>
<p class="arguement"><strong>selector</strong>A selector string to filter the descendants of the selected elements that trigger the event. If the selector is <code>null</code> or omitted, the event is always triggered when it reaches the selected element.</p>
<p class="arguement"><strong>data</strong>Data to be passed to the handler in <a href="/event.data"><code>event.data</code></a> when an event is triggered.</p>
<p class="arguement"><strong>handler</strong>A function to execute when the event is triggered. The value <code>false</code> is also allowed as a shorthand for a function that simply does <code>return false</code>.</p>
</li>
<li class="signature" id="on-events-map-selector-data">
<h4 class="name">
<span class="versionAdded">version added: <a href="/category/version/1.7/">1.7</a></span>.on( events-map [, selector] [, data] )</h4>
<p class="arguement"><strong>events-map</strong>A map in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s).</p>
<p class="arguement"><strong>selector</strong>A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element.</p>
<p class="arguement"><strong>data</strong>Data to be passed to the handler in <a href="http://api.jquery.com/event.data"><code>event.data</code></a> when an event occurs.</p>
</li>
</ul>
<div class="longdesc">
<p>The <code>.on()</code> method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the <code>.on()</code> method provides all functionality required for attaching event handlers. For equivalents to older jQuery event methods, see <a href="http://api.jquery.com/bind"><code>.bind()</code></a>,  <a href="http://api.jquery.com/delegate"><code>.delegate()</code></a>, and <a href="http://api.jquery.com/live"><code>.live()</code></a>. To remove events bound with <code>.on()</code>, see <a href="http://api.jquery.com/off"><code>.off()</code></a>. To attach an event that runs only once and then removes itself, see <a href="http://api.jquery.com/one"><code>.one()</code></a></p>
<h2 id="event-names">Event names and namespaces</h2>
<p>Any event names can be used for the <code>events</code> argument. jQuery will pass through the browser's standard JavaScript event types, calling the <code>handler</code> function when the browser generates events due to user actions such as <code>click</code>. In addition, the <a href="http://api.jquery.com/trigger"><code>.trigger()</code></a> method can trigger both standard browser event names and custom event names to call attached handlers.</p>
<p>An event name can be qualified by <em>event namespaces</em> that simplify removing or triggering the event. For example, <code>"click.myPlugin.simple"</code> defines both the myPlugin and simple namespaces for this particular click event. A click event handler attached via that string could be removed with <code>.off("click.myPlugin")</code> or <code>.off("click.simple")</code> without disturbing other click handlers attached to the elements. Namespaces are similar to CSS classes in that they are not hierarchical; only one name needs to match. Namespaces beginning with an underscore are reserved for jQuery's use.</p>
<p>In the second form of <code>.on()</code>, the <code>events-map</code> argument is a JavaScript Object, or "map". The keys are strings in the same form as the <code>events</code> argument with space-separated event type names and optional namespaces. The value for each key is a function (or <code>false</code> value) that is used as the <code>handler</code> instead of the final argument to the method. In other respects, the two forms are identical in their behavior as described below.</p>
<h2 id="direct-and-delegated-events">Direct and delegated events</h2>
<p>The majority of browser events <em>bubble</em>, or <em>propagate</em>, from the deepest, innermost element (the <strong>event target</strong>) in the document where they occur all the way up to the body and the <code>document</code> element. In Internet Explorer 8 and lower, a few events such as <code>change</code> and <code>submit</code> do not natively bubble but jQuery patches these to bubble and create consistent cross-browser behavior. The <code>focus</code> and <code>blur</code> events are specified by the W3C to not bubble, but jQuery defines cross-browser <code>focusin</code> and <code>focusout</code> events that do bubble.</p>
<p>If <code>selector</code> is omitted or is null, the event handler is referred to as <em>direct</em> or <em>directly-bound</em>. The handler is called every time an event occurs on the selected elements, whether it occurs directly on the element or bubbles from a descendant (inner) element.</p>
<p>When a <code>selector</code> is provided, the event handler is referred to as <em>delegated</em>. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.</p>
<p><strong>Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to <code>.on()</code>.</strong> To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers <em>after</em> the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.</p>
<p>Delegated events have the advantage that they can process events from <em>descendant elements</em> that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or <code>document</code> if the event handler wants to monitor all bubbling events in the document. The <code>document</code> element is available in the <code>head</code> of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.</p>
<p>In addition to their ability to handle events on descendant elements not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its <code>tbody</code>, this example attaches a handler to 1,000 elements:</p>
<pre>
$("#dataTable tbody tr").on("click", function(event){
	alert($(this).text());
});
</pre>
<p>A delegated-events approach attaches an event handler to only one element, the tbody, and the event only needs to bubble up one level (from the clicked <code>tr</code> to <code>tbody</code>):</p>
<pre>
$("#dataTable tbody").on("click", "tr", function(event){
	alert($(this).text());
});
</pre>
<h2 id="event-handler">The event handler and its environment</h2>
<p>The <code>handler</code> argument is a function (or the value <code>false</code>, see below), and is required unless the <code>events-map</code> form is used. You can provide an anonymous handler function at the point of the <code>.on()</code> call, as the examples have done above, or declare a named function and pass its name:</p>
<pre>
function notify() { alert("clicked"); }
$("button").on("click", notify);
</pre>
<p>When the browser triggers an event or other JavaScript calls jQuery's <code>.trigger()</code> method, jQuery passes the handler an <a href="http://api.jquery.com/event-object"><code>event object</code></a> it can use to analyze and change the status of the event. This object is a <em>normalized subset</em> of data provided by the browser; the browser's unmodified native event object is available in <a href="http://api.jquery.com/event.originalEvent"><code>event.originalEvent</code></a>. For example, <a href="http://api.jquery.com/event.type"><code>event.type</code></a> contains the event name (e.g., "resize") and <a href="http://api.jquery.com/event.target"><code>event.target</code></a> indicates the deepest (innermost) element where the event occurred.</p>
<p>By default, most events bubble up from the original event target to the <code>document</code> element. At each element along the way, jQuery calls any matching event handlers that have been attached. A handler can prevent the event from bubbling further up the document tree (and thus prevent handlers on those elements from running) by calling <code>event.stopPropagation()</code>. Any other handlers attached on the current element <em>will</em> run however. To prevent that, call <code>event.stopImmediatePropagation()</code>. (Event handlers bound to an element are called in the same order that they were bound.)</p>
<p>Similarly, a handler can call <code>event.preventDefault()</code> to cancel any default action that the browser may have for this event; for example, the default action on a <code>click</code> event is to follow the link. Not all browser events have default actions, and not all default actions can be canceled. See the <a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-types-list">W3C Events Specification</a> for details.</p>
<p>Returning <code>false</code> from an event handler will automatically call <code>event.stopPropagation()</code> and <code>event.preventDefault()</code>. A <code>false</code> value can also be passed for the <code>handler</code> as a shorthand for <code>function(){ return false; }</code>. So, <code>$("a.disabled").on("click", false);</code> attaches an event handler to all links with class "disabled" that prevents them from being followed when they are clicked and also stops the event from bubbling. </p>
<p>When jQuery calls a handler, the <code>this</code> keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matching <code>selector</code>. (Note that <code>this</code> may not be equal to <code>event.target</code> if the event has bubbled from a descendant element.) To create a jQuery object from the element so that it can be used with jQuery methods, use <code>$(this)</code>.</p>
<h2 id="passing-data">Passing data to the handler</h2>
<p>If a <code>data</code> argument is provided to <code>.on()</code> and is not <code>null</code> or <code>undefined</code>, it is passed to the handler in the <a href="http://api.jquery.com/event.data"><code>event.data</code></a> property each time an event is triggered. The <code>data</code> argument can be any type, but if a string is used the <code>selector</code> must either be provided or explicitly passed as <code>null</code> so that the data is not mistaken for a selector. Best practice is to use an object (map) so that multiple values can be passed as properties.</p>
<p>The same event handler can be bound to an element multiple times. This is especially useful when the <code>event.data</code> feature is being used, or when other unique data resides in a closure around the event handler function. For example:</p>
<pre>
function greet(event) { alert("Hello "+event.data.name); }
$("button").on("click", { name: "Karl" }, greet);
$("button").on("click", { name: "Addy" }, greet);
</pre>
<p>The above code will generate two different alerts when the button is clicked.</p>
<p>As an alternative or in addition to the <code>data</code> argument provided to the <code>.on()</code> method, you can also pass data to an event handler using a second argument to <a href="http://api.jquery.com/trigger">.trigger()</a> or <a href="http://api.jquery.com/triggerHandler">.triggerHandler()</a>.</p>
<h2 id="event-performance">Event performance</h2>
<p>In most cases, an event such as <code>click</code> occurs infrequently and performance is not a significant concern. However, high frequency events such as <code>mousemove</code> or <code>scroll</code> can fire dozens of times per second, and in those cases it becomes more important to use events judiciously. Performance can be increased by reducing the amount of work done in the handler itself, caching information needed by the handler rather than recalculating it, or by rate-limiting the number of actual page updates using <code>setTimeout</code>.</p>
<p>Attaching many delegated event handlers near the top of the document tree can degrade performance. Each time the event occurs, jQuery must compare all selectors of all attached events of that type to every element in the path from the event target up to the top of the document. For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of <code>document</code> or <code>document.body</code> for delegated events on large documents.</p>
<p>jQuery can process simple selectors of the form <code>tag#id.class</code> very quickly when they are used to filter delegated events. So, <code>"#myForm"</code>, <code>"a.external"</code>, and <code>"button"</code> are all fast selectors. Delegated events that use more complex selectors, particularly hierarchical ones, can be several times slower--although they are still fast enough for most applications. Hierarchical selectors can often be avoided simply by attaching the handler to a more appropriate point in the document. For example, instead of <code>$("body").on("click", "#commentForm .addNew", addComment)</code> use <code>$("#commentForm").on("click", ".addNew", addComment)</code>.</p>
<h2 id="additional-notes">Additional notes</h2>
<p>There are shorthand methods for some events such as <a href="/click"><code>.click()</code></a> that can be used to attach or trigger event handlers. For a complete list of shorthand methods, see the <a href="http://api.jquery.com/category/events/">events category</a>.</p>
<p>Although not recommended, the pseudo-event-name <code>"hover"</code> can be used as a shorthand for <code>"mouseenter mouseleave"</code>. Do not confuse it with the <a href="http//api.jquery.com/hover"><code>.hover()</code></a> method, which accepts <em>two</em> functions. There is only one handler function attached by the pseudo-event-name <code>"hover"</code>; the handler should examine <code>event.type</code> to determine whether the event is <code>mouseenter</code> or <code>mouseleave</code>.</p>
<p>jQuery's event system requires that a DOM element allow attaching data via a property on the element, so that events can be tracked and delivered. The <code>object</code>, <code>embed</code>, and <code>applet</code> elements cannot attach data, and therefore cannot have jQuery events bound to them.</p>
<p>The <code>error</code> event on the <code>window</code> object uses nonstandard arguments and return value conventions, so it is not supported by jQuery. Instead, assign a handler function directly to the <code>window.onerror</code> property.</p>
<p>In Internet Explorer 8 and lower, the <code>paste</code> and <code>reset</code> events do not bubble and are not supported for use with delegation. They <em>can</em> be used when the event handler is directly attached to the element generating the event.</p>
</div>
<h3>Examples:</h3>
<div class="entry-examples" id="entry-examples">
<div id="example-0">
<h4>Example: <span class="desc">Display a paragraph's text in an alert when it is clicked:</span>
</h4>
<pre class="prettyprint"><code class="example">$("p").on("click", function(){
alert( $(this).text() );
});</code></pre>
</div>
<div id="example-1">
<h4>Example: <span class="desc">Pass data to the event handler, which is specified here by name:</span>
</h4>
<pre class="prettyprint"><code class="example">function myHandler(event) {
alert(event.data.foo);
}
$("p").on("click", {foo: "bar"}, myHandler)</code></pre>
</div>
<div id="example-2">
<h4>Example: <span class="desc">Cancel a form submit action and prevent the event from bubbling up by returning false:</span>
</h4>
<pre class="prettyprint"><code class="example">$("form").on("submit", false)</code></pre>
</div>
<div id="example-3">
<h4>Example: <span class="desc">Cancel only the default action by using .preventDefault().</span>
</h4>
<pre class="prettyprint"><code class="example">$("form").on("submit", function(event) {
  event.preventDefault();
});</code></pre>
</div>
<div id="example-4">
<h4>Example: <span class="desc">Stop submit events from bubbling without preventing form submit, using .stopPropagation().</span>
</h4>
<pre class="prettyprint"><code class="example">$("form").on("submit", function(event) {
  event.stopPropagation();
});</code></pre>
</div>
<div id="example-5">
<h4>Example: <span class="desc">Attach and trigger custom (non-browser) events.</span>
</h4>
<pre class="prettyprint"><code class="example demo-code">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;style&gt;
p { color:red; }
span { color:blue; }
&lt;/style&gt;
  &lt;script src="http://code.jquery.com/jquery-1.7rc2.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;p&gt;Has an attached custom event.&lt;/p&gt;
&lt;button&gt;Trigger custom event&lt;/button&gt;
&lt;span style="display:none;"&gt;&lt;/span&gt;
&lt;script&gt;

$("p").on("myCustomEvent", function(e, myName, myValue){
  $(this).text(myName + ", hi there!");
  $("span").stop().css("opacity", 1)
    .text("myName = " + myName)
    .fadeIn(30).fadeOut(1000);
});
$("button").click(function () {
  $("p").trigger("myCustomEvent", [ "John" ]);
});

&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;</code></pre>
<h4>Demo:</h4>
<div class="demo code-demo"></div>
</div>
<div id="example-6">
<h4>Example: <span class="desc">Attach multiple event handlers simultaneously using a map.</span>
</h4>
<pre class="prettyprint"><code class="example">$("div.test").on({
  click: function(){
    $(this).addClass("active");
  },
  mouseenter: function(){
    $(this).addClass("inside");
  },
  mouseleave: function(){
    $(this).removeClass("inside");
  }
});</code></pre>
</div>
<div id="example-7">
<h4>Example: <span class="desc">Click any paragraph to add another after it. Note that .on() allows a click event on any paragraph--even new ones--since the event is handled by the ever-present body element after it bubbles to there.</span>
</h4>
<pre class="prettyprint"><code class="example demo-code">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;style&gt;
  p { background:yellow; font-weight:bold; cursor:pointer; 
      padding:5px; }
  p.over { background: #ccc; }
  span { color:red; }
  &lt;/style&gt;
  &lt;script src="http://code.jquery.com/jquery-1.7rc2.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;p&gt;Click me!&lt;/p&gt;

  &lt;span&gt;&lt;/span&gt;
&lt;script&gt;
    var count = 0;
    $("body").on("click", "p", function(){
      $(this).after("&lt;p&gt;Another paragraph! "+(++count)+"&lt;/p&gt;");
    });
&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;</code></pre>
<h4>Demo:</h4>
<div class="demo code-demo"></div>
</div>
<div id="example-8">
<h4>Example: <span class="desc">Display each paragraph's text in an alert box whenever it is clicked:</span>
</h4>
<pre class="prettyprint"><code class="example">$("body").on("click", "p", function(){
  alert( $(this).text() );
});</code></pre>
</div>
<div id="example-9">
<h4>Example: <span class="desc">Cancel a link's default action using the preventDefault method.</span>
</h4>
<pre class="prettyprint"><code class="example">$("body").on("click", "a", function(event){
  event.preventDefault();
});</code></pre>
</div>
<div id="example-10">
<h4>Example: <span class="desc">Attach handlers for custom (non-browser) event names.</span>
</h4>
<pre class="prettyprint"><code class="example demo-code">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;style&gt;
  p { color:red; }
  span { color:blue; }
  &lt;/style&gt;
  &lt;script src="http://code.jquery.com/jquery-1.7rc2.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;p&gt;Has an attached custom event.&lt;/p&gt;
  &lt;button&gt;Trigger custom event&lt;/button&gt;
  &lt;span style="display:none;"&gt;&lt;/span&gt;
&lt;script&gt;

    $("body").on("myCustomEvent", "p", function(e, myName, myValue){
      $(this).text("Hi there!");
      $("span").stop().css("opacity", 1)
               .text("myName = " + myName)
               .fadeIn(30).fadeOut(1000);
    });
    $("button").click(function () {
      $("p").trigger("myCustomEvent");
    });

&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;</code></pre>
<h4>Demo:</h4>
<div class="demo code-demo"></div>
</div>
</div>
</div>
</div>

        </div>

</body></html>