|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989 |
- <!doctype html><!-- This is a valid HTML5 document. -->
- <!-- Screen readers, SEO, extensions and so on. -->
- <html lang=fr>
- <!-- Has to be within the first 1024 bytes, hence before the <title>
- See: https://www.w3.org/TR/2012/CR-html5-20121217/document-metadata.html#charset -->
- <meta charset=utf-8>
- <!-- Why no `X-UA-Compatible` meta: https://stackoverflow.com/a/6771584 -->
- <!-- The viewport meta is quite crowded and we are responsible for that.
- See: https://codepen.io/tigt/post/meta-viewport-for-2015 -->
- <meta name=viewport content="width=device-width,minimum-scale=1,initial-scale=1,shrink-to-fit=no">
- <!-- Required to make a valid HTML5 document. -->
- <title>You Don't Need jQuery! (archive) — David Larlet</title>
- <!-- Generated from https://realfavicongenerator.net/ such a mess. -->
- <link rel="apple-touch-icon" sizes="180x180" href="/static/david/icons/apple-touch-icon.png">
- <link rel="icon" type="image/png" sizes="32x32" href="/static/david/icons/favicon-32x32.png">
- <link rel="icon" type="image/png" sizes="16x16" href="/static/david/icons/favicon-16x16.png">
- <link rel="manifest" href="/manifest.json">
- <link rel="mask-icon" href="/static/david/icons/safari-pinned-tab.svg" color="#5bbad5">
- <link rel="shortcut icon" href="/static/david/icons/favicon.ico">
- <meta name="apple-mobile-web-app-title" content="David Larlet">
- <meta name="application-name" content="David Larlet">
- <meta name="msapplication-TileColor" content="#da532c">
- <meta name="msapplication-config" content="/static/david/icons/browserconfig.xml">
- <meta name="theme-color" content="#f0f0ea">
- <!-- That good ol' feed, subscribe :p. -->
- <link rel=alternate type="application/atom+xml" title=Feed href="/david/log/">
-
- <meta name="robots" content="noindex, nofollow">
- <meta content="origin-when-cross-origin" name="referrer">
- <!-- Canonical URL for SEO purposes -->
- <link rel="canonical" href="http://blog.garstasio.com/you-dont-need-jquery/events/">
-
- <style>
- /* http://meyerweb.com/eric/tools/css/reset/ */
- html, body, div, span,
- h1, h2, h3, h4, h5, h6, p, blockquote, pre,
- a, abbr, address, big, cite, code,
- del, dfn, em, img, ins,
- small, strike, strong, tt, var,
- dl, dt, dd, ol, ul, li,
- fieldset, form, label, legend,
- table, caption, tbody, tfoot, thead, tr, th, td,
- article, aside, canvas, details, embed,
- figure, figcaption, footer, header, hgroup,
- menu, nav, output, ruby, section, summary,
- time, mark, audio, video {
- margin: 0;
- padding: 0;
- border: 0;
- font-size: 100%;
- font: inherit;
- vertical-align: baseline;
- }
- /* HTML5 display-role reset for older browsers */
- article, aside, details, figcaption, figure,
- footer, header, hgroup, menu, nav, section { display: block; }
- body { line-height: 1; }
- blockquote, q { quotes: none; }
- blockquote:before, blockquote:after,
- q:before, q:after {
- content: '';
- content: none;
- }
- table {
- border-collapse: collapse;
- border-spacing: 0;
- }
-
- /* http://practicaltypography.com/equity.html */
- /* https://calendar.perfplanet.com/2016/no-font-face-bulletproof-syntax/ */
- /* https://www.filamentgroup.com/lab/js-web-fonts.html */
- @font-face {
- font-family: 'EquityTextB';
- src: url('/static/david/css/fonts/Equity-Text-B-Regular-webfont.woff2') format('woff2'),
- url('/static/david/css/fonts/Equity-Text-B-Regular-webfont.woff') format('woff');
- font-weight: 300;
- font-style: normal;
- font-display: swap;
- }
- @font-face {
- font-family: 'EquityTextB';
- src: url('/static/david/css/fonts/Equity-Text-B-Italic-webfont.woff2') format('woff2'),
- url('/static/david/css/fonts/Equity-Text-B-Italic-webfont.woff') format('woff');
- font-weight: 300;
- font-style: italic;
- font-display: swap;
- }
- @font-face {
- font-family: 'EquityTextB';
- src: url('/static/david/css/fonts/Equity-Text-B-Bold-webfont.woff2') format('woff2'),
- url('/static/david/css/fonts/Equity-Text-B-Bold-webfont.woff') format('woff');
- font-weight: 700;
- font-style: normal;
- font-display: swap;
- }
-
- @font-face {
- font-family: 'ConcourseT3';
- src: url('/static/david/css/fonts/concourse_t3_regular-webfont-20190806.woff2') format('woff2'),
- url('/static/david/css/fonts/concourse_t3_regular-webfont-20190806.woff') format('woff');
- font-weight: 300;
- font-style: normal;
- font-display: swap;
- }
-
-
- /* http://practice.typekit.com/lesson/caring-about-opentype-features/ */
- body {
- /* http://www.cssfontstack.com/ Palatino 99% Win 86% Mac */
- font-family: "EquityTextB", Palatino, serif;
- background-color: #f0f0ea;
- color: #07486c;
- font-kerning: normal;
- -moz-osx-font-smoothing: grayscale;
- -webkit-font-smoothing: subpixel-antialiased;
- text-rendering: optimizeLegibility;
- font-variant-ligatures: common-ligatures contextual;
- font-feature-settings: "kern", "liga", "clig", "calt";
- }
- pre, code, kbd, samp, var, tt {
- font-family: 'TriplicateT4c', monospace;
- }
- em {
- font-style: italic;
- color: #323a45;
- }
- strong {
- font-weight: bold;
- color: black;
- }
- nav {
- background-color: #323a45;
- color: #f0f0ea;
- display: flex;
- justify-content: space-around;
- padding: 1rem .5rem;
- }
- nav:last-child {
- border-bottom: 1vh solid #2d7474;
- }
- nav a {
- color: #f0f0ea;
- }
- nav abbr {
- border-bottom: 1px dotted white;
- }
-
- h1 {
- border-top: 1vh solid #2d7474;
- border-bottom: .2vh dotted #2d7474;
- background-color: #e3e1e1;
- color: #323a45;
- text-align: center;
- padding: 5rem 0 4rem 0;
- width: 100%;
- font-family: 'ConcourseT3';
- display: flex;
- flex-direction: column;
- }
- h1.single {
- padding-bottom: 10rem;
- }
- h1 span {
- position: absolute;
- top: 1vh;
- left: 20%;
- line-height: 0;
- }
- h1 span a {
- line-height: 1.7;
- padding: 1rem 1.2rem .6rem 1.2rem;
- border-radius: 0 0 6% 6%;
- background: #2d7474;
- font-size: 1.3rem;
- color: white;
- text-decoration: none;
- }
- h2 {
- margin: 4rem 0 1rem;
- border-top: .2vh solid #2d7474;
- padding-top: 1vh;
- }
- h3 {
- text-align: center;
- margin: 3rem 0 .75em;
- }
- hr {
- height: .4rem;
- width: .4rem;
- border-radius: .4rem;
- background: #07486c;
- margin: 2.5rem auto;
- }
- time {
- display: bloc;
- margin-left: 0 !important;
- }
- ul, ol {
- margin: 2rem;
- }
- ul {
- list-style-type: square;
- }
- a {
- text-decoration-skip-ink: auto;
- text-decoration-thickness: 0.05em;
- text-underline-offset: 0.09em;
- }
- article {
- max-width: 50rem;
- display: flex;
- flex-direction: column;
- margin: 2rem auto;
- }
- article.single {
- border-top: .2vh dotted #2d7474;
- margin: -6rem auto 1rem auto;
- background: #f0f0ea;
- padding: 2rem;
- }
- article p:last-child {
- margin-bottom: 1rem;
- }
- p {
- padding: 0 .5rem;
- margin-left: 3rem;
- }
- p + p,
- figure + p {
- margin-top: 2rem;
- }
-
- blockquote {
- background-color: #e3e1e1;
- border-left: .5vw solid #2d7474;
- display: flex;
- flex-direction: column;
- align-items: center;
- padding: 1rem;
- margin: 1.5rem;
- }
- blockquote cite {
- font-style: italic;
- }
- blockquote p {
- margin-left: 0;
- }
-
- figure {
- border-top: .2vh solid #2d7474;
- background-color: #e3e1e1;
- text-align: center;
- padding: 1.5rem 0;
- margin: 1rem 0 0;
- font-size: 1.5rem;
- width: 100%;
- }
- figure img {
- max-width: 250px;
- max-height: 250px;
- border: .5vw solid #323a45;
- padding: 1px;
- }
- figcaption {
- padding: 1rem;
- line-height: 1.4;
- }
- aside {
- display: flex;
- flex-direction: column;
- background-color: #e3e1e1;
- padding: 1rem 0;
- border-bottom: .2vh solid #07486c;
- }
- aside p {
- max-width: 50rem;
- margin: 0 auto;
- }
-
- /* https://fvsch.com/code/css-locks/ */
- p, li, pre, code, kbd, samp, var, tt, time, details, figcaption {
- font-size: 1rem;
- line-height: calc( 1.5em + 0.2 * 1rem );
- }
- h1 {
- font-size: 1.9rem;
- line-height: calc( 1.2em + 0.2 * 1rem );
- }
- h2 {
- font-size: 1.6rem;
- line-height: calc( 1.3em + 0.2 * 1rem );
- }
- h3 {
- font-size: 1.35rem;
- line-height: calc( 1.4em + 0.2 * 1rem );
- }
- @media (min-width: 20em) {
- /* The (100vw - 20rem) / (50 - 20) part
- resolves to 0-1rem, depending on the
- viewport width (between 20em and 50em). */
- p, li, pre, code, kbd, samp, var, tt, time, details, figcaption {
- font-size: calc( 1rem + .6 * (100vw - 20rem) / (50 - 20) );
- line-height: calc( 1.5em + 0.2 * (100vw - 50rem) / (20 - 50) );
- margin-left: 0;
- }
- h1 {
- font-size: calc( 1.9rem + 1.5 * (100vw - 20rem) / (50 - 20) );
- line-height: calc( 1.2em + 0.2 * (100vw - 50rem) / (20 - 50) );
- }
- h2 {
- font-size: calc( 1.5rem + 1.5 * (100vw - 20rem) / (50 - 20) );
- line-height: calc( 1.3em + 0.2 * (100vw - 50rem) / (20 - 50) );
- }
- h3 {
- font-size: calc( 1.35rem + 1.5 * (100vw - 20rem) / (50 - 20) );
- line-height: calc( 1.4em + 0.2 * (100vw - 50rem) / (20 - 50) );
- }
- }
- @media (min-width: 50em) {
- /* The right part of the addition *must* be a
- rem value. In this example we *could* change
- the whole declaration to font-size:2.5rem,
- but if our baseline value was not expressed
- in rem we would have to use calc. */
- p, li, pre, code, kbd, samp, var, tt, time, details, figcaption {
- font-size: calc( 1rem + .6 * 1rem );
- line-height: 1.5em;
- }
- p, li, pre, details {
- margin-left: 3rem;
- }
- h1 {
- font-size: calc( 1.9rem + 1.5 * 1rem );
- line-height: 1.2em;
- }
- h2 {
- font-size: calc( 1.5rem + 1.5 * 1rem );
- line-height: 1.3em;
- }
- h3 {
- font-size: calc( 1.35rem + 1.5 * 1rem );
- line-height: 1.4em;
- }
- figure img {
- max-width: 500px;
- max-height: 500px;
- }
- }
-
- figure.unsquared {
- margin-bottom: 1.5rem;
- }
- figure.unsquared img {
- height: inherit;
- }
-
-
-
- @media print {
- body { font-size: 100%; }
- a:after { content: " (" attr(href) ")"; }
- a, a:link, a:visited, a:after {
- text-decoration: underline;
- text-shadow: none !important;
- background-image: none !important;
- background: white;
- color: black;
- }
- abbr[title] { border-bottom: 0; }
- abbr[title]:after { content: " (" attr(title) ")"; }
- img { page-break-inside: avoid; }
- @page { margin: 2cm .5cm; }
- h1, h2, h3 { page-break-after: avoid; }
- p3 { orphans: 3; widows: 3; }
- img {
- max-width: 250px !important;
- max-height: 250px !important;
- }
- nav, aside { display: none; }
- }
-
- ul.with_columns {
- column-count: 1;
- }
- @media (min-width: 20em) {
- ul.with_columns {
- column-count: 2;
- }
- }
- @media (min-width: 50em) {
- ul.with_columns {
- column-count: 3;
- }
- }
- ul.with_two_columns {
- column-count: 1;
- }
- @media (min-width: 20em) {
- ul.with_two_columns {
- column-count: 1;
- }
- }
- @media (min-width: 50em) {
- ul.with_two_columns {
- column-count: 2;
- }
- }
-
- .gallery {
- display: flex;
- flex-wrap: wrap;
- justify-content: space-around;
- }
- .gallery figure img {
- margin-left: 1rem;
- margin-right: 1rem;
- }
- .gallery figure figcaption {
- font-family: 'ConcourseT3'
- }
-
- footer {
- font-family: 'ConcourseT3';
- display: flex;
- flex-direction: column;
- border-top: 3px solid white;
- padding: 4rem 0;
- background-color: #07486c;
- color: white;
- }
- footer > * {
- max-width: 50rem;
- margin: 0 auto;
- }
- footer a {
- color: #f1c40f;
- }
- footer .avatar {
- width: 200px;
- height: 200px;
- border-radius: 50%;
- float: left;
- -webkit-shape-outside: circle();
- shape-outside: circle();
- margin-right: 2rem;
- padding: 2px 5px 5px 2px;
- background: white;
- border-left: 1px solid #f1c40f;
- border-top: 1px solid #f1c40f;
- border-right: 5px solid #f1c40f;
- border-bottom: 5px solid #f1c40f;
- }
- </style>
-
- <h1>
- <span><a id="jumper" href="#jumpto" title="Un peu perdu ?">?</a></span>
- You Don't Need jQuery! (archive)
- <time>Pour la pérennité des contenus liés. Non-indexé, retrait sur simple email.</time>
- </h1>
- <section>
- <article>
- <h3><a href="http://blog.garstasio.com/you-dont-need-jquery/events/">Source originale du contenu</a></h3>
- <div class="entry">
- <p>In this fifth installment of "You Don't Need jQuery (anymore)", I'm going to talk about dealing with events in the browser without jQuery. As always, each section will cover the jQuery approach, followed by a solution using the native Web API instead. After reading this post on events, you should be confident enough to deal with events in your own project without using jQuery.</p>
-
- <p>As I've mentioned (many times) before, this blog is not about bad-mouthing jQuery. jQuery is, without a doubt, ubiquitous in the world of web development. In the earlier days of web development, jQuery was required to smooth out the significant implementation differences and bugs found in various browsers when dealing with the DOM and the Web API as a whole. Also, the Web API was quite primitive at the time, in some respects, and jQuery helped to make development a bit more intuitive.</p>
-
- <p>Browsers, and the Web API, have come a long way in the last several years. You can do a lot without jQuery, and I have mostly avoided jQuery in my new projects for the last several years. The jQuery approach may take less keystrokes, or look a bit more elegant in some cases. That's fine, but the point of this blog isn't to help you reduce the number of keystrokes, or write more beautiful code.</p>
-
- <p>My last few posts covered selecting elements, DOM manipulation, and ajax requests. In those instances, the Web API is fairly elegant, and not much is gained by using jQuery. However, when dealing with events, the Web API is admittedly lacking in the elegance and convenience departments, even in modern browsers in some cases. That's ok, because this blog is about helping you understand the Web API so that you can avoid blindly depending on jQuery to develop your web applications. When you rely on a library to develop a large part of your application, you had better understand how the low-level API works. Otherwise you will find troubleshooting unexpected behaviors that will inevitably pop up from time to time to be quite frustrating. Keep in mind that <a href="https://github.com/jquery/jquery/issues">jQuery has bugs of its own</a>.</p>
-
- <p><strong>This post on events will primarily focus on event handling in modern browsers. We're going to define modern browsers as anything newer (and including) Internet Explorer 9.</strong> This is a commonly accepted definition, in my experience. That said, this post on events will also illustrate how jQuery was especially important when Internet Explorer 8 was commonly supported, and how you you likely will want to consider pulling in a events library, or even jQuery, to assist if you are in the unusual and unfortunate position to require support for Internet Explorer 8 or older in a new web application.</p>
-
- <p>Keep in mind that the examples, descriptions, and comparisons below do not represent exhaustive references. This is all just something to help you understand what the Web API provides. Both jQuery and the Web API allow you to perform much more complex operations than the ones demonstrated here. I am merely supplying you with the basic knowledge/building blocks required to build something much more complex.</p>
-
- <ol>
- <li><a href="#sending-native-(dom)-events">Sending Native (DOM) Events</a></li>
- <li><a href="#sending-custom-events">Sending Custom Events</a></li>
- <li><a href="#listening-for-events">Listening For Events</a></li>
- <li><a href="#removing-event-handlers">Removing Event Handlers</a></li>
- <li><a href="#modifying-events">Modifying Events</a></li>
- <li><a href="#event-delgation">Event Delegation</a></li>
- <li><a href="#keyboard-events">Keyboard Events</a></li>
- <li><a href="#mouse-events">Mouse Events</a></li>
- <li><a href="#browser-load-events">Browser Load Events</a></li>
- <li><a href="#ancient-browser-support">Ancient Browser Support</a></li>
- <li><a href="#libraries-to-consider">Libraries to Consider</a></li>
- <li><a href="#next">Next in this Series</a></li>
- </ol>
-
- <h2 id="sending-native-(dom)-events">Sending Native (DOM) Events</h2>
-
- <p>We'll start out simple here with DOM events, that is, events that are defined as part of the <strong>D</strong>ocument <strong>O</strong>bject <strong>M</strong>odel in the W3C (<strong>W</strong>orld <strong>W</strong>ide <strong>W</strong>eb <strong>C</strong>onsortium) specification.</p>
-
- <p>Let's say we have an anchor tag, and we want to programmatically click it using JavaScript.</p>
-
- <h4 id="jquery">jQuery</h4>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">$</span><span class="p">(</span><span class="nx">anchorElement</span><span class="p">).</span><span class="nx">click</span><span class="p">();</span>
- </code></pre></div>
- <p>Well, that was pretty easy! If we <em>really</em> want to do this the jQuery way (for whatever reason) we need to wrap the element so we can access jQuery's API, of course.</p>
-
- <h4 id="web-api">Web API</h4>
-
- <p>The above code will work in any browser available today (even IE6). jQuery certainly doesn't help us here. The code follows the same intuitive syntax if we want to trigger some other DOM events, such as <code>focus</code> and <code>blur</code>, or <code>submit</code> on a <code><form></code>.</p>
-
- <h2 id="sending-custom-events">Sending Custom Events</h2>
-
- <p>We have an event, "my-custom-event" that we need to trigger. This event must bubble by default, and must be cancellable by a handler.</p>
-
- <h4 id="jquery">jQuery</h4>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">$</span><span class="p">(</span><span class="s1">'some-element'</span><span class="p">).</span><span class="nx">trigger</span><span class="p">(</span><span class="s1">'my-custom-event'</span><span class="p">);</span>
- </code></pre></div>
- <p>The above code will fire the custom event starting with the <code>someElement</code> element. The event will bubble up the DOM by default. jQuery actually walks the event up the DOM itself, triggering any jQuery-specific event handlers and/or functions on each element that correspond to the event name (such as <code>click()</code> for a "click" event).</p>
-
- <h4 id="web-api">Web API</h4>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">event</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">createEvent</span><span class="p">(</span><span class="s1">'Event'</span><span class="p">);</span>
- <span class="nx">event</span><span class="p">.</span><span class="nx">initEvent</span><span class="p">(</span><span class="s1">'my-custom-event'</span><span class="p">,</span> <span class="kc">true</span><span class="p">,</span> <span class="kc">true</span><span class="p">);</span> <span class="c1">//can bubble, and is cancellable</span>
- <span class="nx">someElement</span><span class="p">.</span><span class="nx">dispatchEvent</span><span class="p">(</span><span class="nx">event</span><span class="p">);</span>
- </code></pre></div>
- <p>The above code will work in all browsers. But, the <code>createEvent</code> method on <code>document</code> has, for the most part, been deprecated. All browsers, to my knowledge, continue to support it though.</p>
-
- <p>The more "modern" approach involves using the <code>CustomEvent</code> constructor:</p>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">event</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">CustomEvent</span><span class="p">(</span><span class="s1">'my-custom-event'</span><span class="p">,</span> <span class="p">{</span><span class="nx">bubbles</span><span class="o">:</span> <span class="kc">true</span><span class="p">,</span> <span class="nx">cancelable</span><span class="o">:</span> <span class="kc">true</span><span class="p">});</span>
- <span class="nx">someElement</span><span class="p">.</span><span class="nx">dispatchEvent</span><span class="p">(</span><span class="nx">event</span><span class="p">);</span>
- </code></pre></div>
- <p>Unfortunately, the <code>CustomEvent</code> constructor is not supported in any version of Internet Explorer to date. This will work in all other modern browsers though. If you need to support Internet Explorer (and we all do) you will need fall back to the initial example in this section. For the most part, it is probably best to continue to use <code>createEvent</code> if it is supported by the browser. If newer browsers begin to remove <code>createEvent</code> from their implementation of the Web API, you should be able to easily detect this and use <code>CustomEvent</code> instead.</p>
-
- <h2 id="listening-for-events">Listening For Events</h2>
-
- <p>The syntax required to consume an event, DOM or custom, is very similar for modern browsers between the jQuery and native approaches. For this example, we will set up some code that will notify us when an element we're interested in has been clicked (either programmatically or via user interaction):</p>
-
- <h4 id="jquery">jQuery</h4>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">$</span><span class="p">(</span><span class="nx">someElement</span><span class="p">).</span><span class="nx">on</span><span class="p">(</span><span class="s1">'click'</span><span class="p">,</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
- <span class="c1">// TODO event handler logic</span>
- <span class="p">});</span>
- </code></pre></div>
- <p>You can also make use of the <code>click</code> method, which allows you to register an event handler if the first argument is a handler function:</p>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">$</span><span class="p">(</span><span class="nx">someElement</span><span class="p">).</span><span class="nx">click</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
- <span class="c1">// TODO event handler logic</span>
- <span class="p">});</span>
- </code></pre></div>
- <h4 id="web-api">Web API</h4>
-
- <p>As mentioned before, the syntax for registering an event handler using the native browser API in modern browsers (which includes IE9) is refreshingly similar to jQuery:</p>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">someElement</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">'click'</span><span class="p">,</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
- <span class="c1">// TODO event handler logic</span>
- <span class="p">});</span>
- </code></pre></div>
- <p>Note that all elements (for the most part) inherit from the <code>Node</code> interface, which itself inherits from the <code>EventTarget</code> interface. The first version of Internet Explorer that includes support for the <code>addEventListener</code> method on the <code>EventTarget</code> interface is IE9.</p>
-
- <h2 id="removing-event-handlers">Removing Event Handlers</h2>
-
- <p>Whether you use jQuery or vanilla JavaScript, you must keep track of your original event handler function in order to un-register it. While jQuery provides a convenience method to remove "all" event handlers of a particular type from a specific element, it is important to understand that this will <strong>only</strong> remove any event handlers that were attached to that element via jQuery (ignoring any that may have been attached <em>directly</em> via <code>addEventListener</code>). This is due to the fact that the Web API does not provide any way to obtain a list of registered event handlers, nor does it provide a way to blindly remove all event handlers attached to an element.</p>
-
- <p>So, let's say we've previously attached the following click event handler to an element:</p>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">var</span> <span class="nx">myEventHandler</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
- <span class="c1">// handles the event...</span>
- <span class="p">}</span>
- </code></pre></div>
- <p>...and we now want to remove it:</p>
-
- <h4 id="jquery">jQuery</h4>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">$</span><span class="p">(</span><span class="s1">'some-element'</span><span class="p">).</span><span class="nx">off</span><span class="p">(</span><span class="s1">'click'</span><span class="p">,</span> <span class="nx">myEventHandler</span><span class="p">);</span>
- </code></pre></div>
- <h4 id="web-api">Web API</h4>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">someElement</span><span class="p">.</span><span class="nx">removeEventListener</span><span class="p">(</span><span class="s1">'click'</span><span class="p">,</span> <span class="nx">myEventHandler</span><span class="p">);</span>
- </code></pre></div>
- <h2 id="modifying-events">Modifying Events</h2>
-
- <p>The ability to modify an event generally refers to augmenting or squelching the event by one event handler before it reaches other event handlers.</p>
-
- <h3 id="preventing-the-event-from-bubbling-further-up-the-dom">Preventing the event from bubbling further up the DOM</h3>
-
- <p>Here, we want to ensure the event, caught by our event handler, will not reach any additional event handlers positioned on ancestor elements. This will stop the event from bubbling up the DOM.</p>
-
- <h4 id="jquery">jQuery</h4>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">$</span><span class="p">(</span><span class="nx">someEl</span><span class="p">).</span><span class="nx">on</span><span class="p">(</span><span class="s1">'some-event'</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
- <span class="nx">event</span><span class="p">.</span><span class="nx">stopPropagation</span><span class="p">();</span>
- <span class="p">});</span>
- </code></pre></div>
- <h4 id="web-api">Web API</h4>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">someEl</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">'some-event'</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
- <span class="nx">event</span><span class="p">.</span><span class="nx">stopPropagation</span><span class="p">();</span>
- <span class="p">});</span>
- </code></pre></div>
- <p>The syntax between jQuery and the modern Web API here is almost identical.</p>
-
- <h3 id="preventing-the-event-from-hitting-any-additional-handlers-attached-to-the-current-element">Preventing the event from hitting any additional handlers attached to the current element</h3>
-
- <p>Not only do we want to prevent this event from hitting any handlers bound to elements that are ancestors of this one, but we also want to ensure no other event handlers bound to this element are hit either. So, we want to prevent the event from hitting <em>any</em> further event handlers.</p>
-
- <h4 id="jquery">jQuery</h4>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">$</span><span class="p">(</span><span class="nx">someEl</span><span class="p">).</span><span class="nx">on</span><span class="p">(</span><span class="s1">'some-event'</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
- <span class="nx">event</span><span class="p">.</span><span class="nx">stopImmediatePropagation</span><span class="p">();</span>
- <span class="p">});</span>
- </code></pre></div>
- <h4 id="web-api">Web API</h4>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">someEl</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">'some-event'</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
- <span class="nx">event</span><span class="p">.</span><span class="nx">stopImmediatePropagation</span><span class="p">();</span>
- <span class="p">});</span>
- </code></pre></div>
- <p>Again, the syntax between jQuery and the modern Web API here is eerily similar.</p>
-
- <h3 id="preventing-the-event-from-triggering-an-action-defined-by-the-browser">Preventing the event from triggering an action defined by the browser</h3>
-
- <p>Let's say we have the following element:</p>
- <div class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt"><a</span> <span class="na">href=</span><span class="s">"http://fineuploader.com"</span><span class="nt">></span>Go to Fine Uploader<span class="nt"></a></span>
- </code></pre></div>
- <p>...and we want to prevent a click on this anchor from opening the associated page. This will involve adding a click handler to the anchor element and instructing the browser to <em>not</em> execute the its native/default action.</p>
-
- <h4 id="jquery">jQuery</h4>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">$</span><span class="p">(</span><span class="nx">someAnchor</span><span class="p">).</span><span class="nx">on</span><span class="p">(</span><span class="s1">'click'</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
- <span class="nx">event</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span>
- <span class="p">});</span>
- </code></pre></div>
- <h4 id="web-api">Web API</h4>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">someAnchor</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">'click'</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
- <span class="nx">event</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span>
- <span class="p">});</span>
- </code></pre></div>
- <p>Are you seeing a pattern here? The syntax required to deal with events is starting to look about the same between jQuery and the Web API.</p>
-
- <h2 id="event-delegation">Event Delegation</h2>
-
- <p>Suppose you have a list filled with list items that are sensitive to mouse clicks. You could attach a click handler to each individual list item. However, this may be inefficient and slow down your page with a large number of list items. Suppose items are added to this list dynamically. Now attaching a new event handler to each new list item, as it is added, becomes less appealing.</p>
-
- <p>The solution here is event delegation. That is, attach one click handler to the list. When any of the list items are clicked, the event will bubble up to its parent, the list container element. At this point, your one event handler will be hit and you can easily determine, by inspecting the event object, which list item was clicked and respond appropriately.</p>
-
- <p>The markup for such a list may look like this:</p>
- <div class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt"><ul</span> <span class="na">id=</span><span class="s">"my-list"</span><span class="nt">></span>
- <span class="nt"><li></span>foo <span class="nt"><button></span>x<span class="nt"></button></li></span>
- <span class="nt"><li></span>bar <span class="nt"><button></span>x<span class="nt"></button></li></span>
- <span class="nt"><li></span>abc <span class="nt"><button></span>x<span class="nt"></button></li></span>
- <span class="nt"><li></span>123 <span class="nt"><button></span>x<span class="nt"></button></li></span>
- <span class="nt"></ul></span>
- </code></pre></div>
- <p>If the user clicks on the "x" button, the list item should be removed from the list.</p>
-
- <h4 id="jquery">jQuery</h4>
-
- <p>jQuery will set the context of our handler to the element that initially received the click (the <code><button></code>). Also, only <code><button></code> elements inside this list will be examined.</p>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">$</span><span class="p">(</span><span class="s1">'#my-list'</span><span class="p">).</span><span class="nx">on</span><span class="p">(</span><span class="s1">'click'</span><span class="p">,</span> <span class="s1">'BUTTON'</span><span class="p">,</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
- <span class="nx">$</span><span class="p">(</span><span class="k">this</span><span class="p">).</span><span class="nx">parent</span><span class="p">().</span><span class="nx">remove</span><span class="p">();</span>
- <span class="p">});</span>
- </code></pre></div>
- <h4 id="web-api">Web API</h4>
-
- <p>We have to write a couple more lines of code without jQuery, but this still isn't exactly rocket science. The Web API always sets the context of the event handler to the element receiving the click event, which in this case is the list container element. Instead, we need to know which element was initially clicked, which is available in the <code>target</code> property of the provided <code>Event</code> object. We must also ensure that we only act on <code><button></code> clicks.</p>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nb">document</span><span class="p">.</span><span class="nx">getElementById</span><span class="p">(</span><span class="s1">'my-list'</span><span class="p">).</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">'click'</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
- <span class="kd">var</span> <span class="nx">clickedEl</span> <span class="o">=</span> <span class="nx">event</span><span class="p">.</span><span class="nx">target</span><span class="p">;</span>
- <span class="k">if</span><span class="p">(</span><span class="nx">clickedEl</span><span class="p">.</span><span class="nx">tagName</span> <span class="o">===</span> <span class="s1">'BUTTON'</span><span class="p">)</span> <span class="p">{</span>
- <span class="kd">var</span> <span class="nx">listItem</span> <span class="o">=</span> <span class="nx">clickedEl</span><span class="p">.</span><span class="nx">parentNode</span><span class="p">;</span>
- <span class="nx">listItem</span><span class="p">.</span><span class="nx">parentNode</span><span class="p">.</span><span class="nx">removeChild</span><span class="p">(</span><span class="nx">listItem</span><span class="p">);</span>
- <span class="p">}</span>
- <span class="p">});</span>
- </code></pre></div>
- <p>Remember, this isn't about elegant code, it's about exploring and understanding the Web API. After all, jQuery is just a Web API wrapper.</p>
-
- <h2 id="keyboard-events">Keyboard Events</h2>
-
- <p>In this section, I'll show how to handle various keyboard events. I'll also show how to identify which specific key was pressed by the user.</p>
-
- <p>First, we should take a moment to be sure we understand the difference between the three different types of general keyboard events:</p>
-
- <ol>
- <li><code>keydown</code>: Key has been pressed but not yet released. No default action has been performed yet.</li>
- <li><code>keypress</code>: Key has been pressed and a character has registered. This event will fire continuously if the key is held down.</li>
- <li><code>keyup</code>: Pressed key has been released.</li>
- </ol>
-
- <p>Let's say we are building a web application and want to make an interactive tutorial that we've build accessible via an intuitive keyboard shortcut. Anywhere in the application, our users should be able to pull up our help widget via the <code>Ctrl</code>-<code>H</code> key combination.</p>
-
- <h4 id="jquery">jQuery</h4>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">$</span><span class="p">(</span><span class="nb">document</span><span class="p">).</span><span class="nx">keydown</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
- <span class="k">if</span> <span class="p">(</span><span class="nx">event</span><span class="p">.</span><span class="nx">ctrlKey</span> <span class="o">&&</span> <span class="nx">event</span><span class="p">.</span><span class="nx">which</span> <span class="o">===</span> <span class="mi">72</span><span class="p">)</span> <span class="p">{</span>
- <span class="c1">// open help widget</span>
- <span class="p">}</span>
- <span class="p">});</span>
- </code></pre></div>
- <h4 id="web-api">Web API</h4>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nb">document</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">'keydown'</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
- <span class="k">if</span> <span class="p">(</span><span class="nx">event</span><span class="p">.</span><span class="nx">ctrlKey</span> <span class="o">&&</span> <span class="nx">event</span><span class="p">.</span><span class="nx">which</span> <span class="o">===</span> <span class="mi">72</span><span class="p">)</span> <span class="p">{</span>
- <span class="c1">// open help widget</span>
- <span class="p">}</span>
- <span class="p">});</span>
- </code></pre></div>
- <p>Nothing is obviously gained, in this instance, with jQuery. Even the syntax is almost identical between the Web API and jQuery.</p>
-
- <p>Registering for other keyboard events follows a similar pattern:</p>
-
- <h4 id="jquery">jQuery</h4>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">$</span><span class="p">(</span><span class="nx">someElement</span><span class="p">).</span><span class="nx">keypress</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
- <span class="c1">// ...</span>
- <span class="p">});</span>
-
- <span class="nx">$</span><span class="p">(</span><span class="nx">someElement</span><span class="p">).</span><span class="nx">keyup</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
- <span class="c1">// ...</span>
- <span class="p">});</span>
- </code></pre></div>
- <h4 id="web-api">Web API</h4>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">someElement</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">'keypress'</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
- <span class="c1">// ...</span>
- <span class="p">});</span>
-
- <span class="nx">someElement</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">'keyup'</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
- <span class="c1">// ...</span>
- <span class="p">});</span>
- </code></pre></div>
- <p>For more information about keyboard event properties and browser compatibility among the properties of this event, have a look at the <a href="https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent"><code>KeyboardEvent</code> document on Mozilla Developer Network</a>.</p>
-
- <h2 id="mouse-events">Mouse Events</h2>
-
- <p>There are a number of mouse events provided by the Web API, such as "mousedown", "mouseenter", and "mouseover" (to name a few). It isn't particularly interesting to show how to register for and handle these events in jQuery and the Web API. Much like keyboard events, the syntax between the two is almost identical.</p>
-
- <p>Instead, I'm going to focus on one special event that is part of jQuery's API. Of course, the goal here is to create your own code by using the plain 'ole Web API sans jQuery. I'll show you how to do that too.</p>
-
- <h3 id="jquery's-hover-event">jQuery's <code>hover</code> event</h3>
-
- <p>jQuery provides a way to notify you when a mouse pointer has hovered over a specific element, and then again when the mouse pointer leaves this element. For example:</p>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">$</span><span class="p">(</span><span class="s1">'some-element'</span><span class="p">).</span><span class="nx">hover</span><span class="p">(</span>
- <span class="kd">function</span> <span class="nx">hoverIn</span><span class="p">()</span> <span class="p">{</span>
- <span class="c1">// mouse is hovering over this element</span>
- <span class="p">},</span>
-
- <span class="kd">function</span> <span class="nx">hoverOut</span><span class="p">()</span> <span class="p">{</span>
- <span class="c1">// mouse was hovering over this element, but no longer is</span>
- <span class="p">}</span>
- <span class="p">);</span>
- </code></pre></div>
- <p>We can do the same thing with the Web API pretty easily:</p>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">someEl</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">'mouseover'</span><span class="p">,</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
- <span class="c1">// mouse is hovering over this element</span>
- <span class="p">});</span>
-
- <span class="nx">someEl</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">'mouseout'</span><span class="p">,</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
- <span class="c1">// mouse was hovering over this element, but no longer is</span>
- <span class="p">});</span>
- </code></pre></div>
- <p>As I mentioned earlier, mouse events are fairly straightforward to handler with the Web API. For more information on mouse events, have a look at the <a href="https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent"><code>MouseEvent</code> interface documentation on the Mozilla Developer Network</a>.</p>
-
- <h2 id="browser-load-events">Browser Load Events</h2>
-
- <p>When talking about "load" events in the browser, we may be trying to answer any one of the following questions:</p>
-
- <h3 id="when-have-all-elements-on-the-page-fully-loaded-and-rendered-w/-applied-styles?">When have all elements on the page fully loaded and rendered w/ applied styles?</h3>
-
- <p>This event should be fired after:</p>
-
- <ul>
- <li>all markup has been placed on the page</li>
- <li>all stylesheets have been loaded</li>
- <li>all images have loaded</li>
- <li>all iframes have fully loaded</li>
- </ul>
-
- <h4 id="jquery">jQuery</h4>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">$</span><span class="p">(</span><span class="nb">window</span><span class="p">).</span><span class="nx">load</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
- <span class="c1">// page is fully rendered</span>
- <span class="p">})</span>
- </code></pre></div>
- <h4 id="web-api">Web API</h4>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nb">window</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">'load'</span><span class="p">,</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
- <span class="c1">// page is fully rendered</span>
- <span class="p">});</span>
- </code></pre></div>
- <h3 id="when-has-all-static-markup-been-placed-on-the-page?">When has all static markup been placed on the page?</h3>
-
- <p>This event should fire after all markup has been placed on the page.</p>
-
- <h4 id="jquery">jQuery</h4>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">$</span><span class="p">(</span><span class="nb">document</span><span class="p">).</span><span class="nx">ready</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
- <span class="c1">// markup is on the page</span>
- <span class="p">});</span>
- </code></pre></div>
- <p>Note that you can also achieve the same thing in jQuery this way:</p>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">$</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
- <span class="c1">// markup is on the page</span>
- <span class="p">});</span>
- </code></pre></div>
- <h4 id="web-api">Web API</h4>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nb">document</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">'DOMContentLoaded'</span><span class="p">,</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
- <span class="c1">// markup is on the page</span>
- <span class="p">});</span>
- </code></pre></div>
- <p>Note that you will likely want to ensure your script that registers the <code>DOMContentLoaded</code> event handler is placed before any stylesheet <code><link></code> tags, since loading these stylsheets will block any script execution and prolong the <code>DOMContentLoaded</code> event until the defined stylesheets have loaded.</p>
-
- <h3 id="when-has-a-particular-element-on-the-page-fully-loaded?">When has a particular element on the page fully loaded?</h3>
-
- <p>In addition to <code>window</code>, load events are associated with a number of elements, such as <code><img></code>, <code><link></code>, and <code><script></code>. The most common use of this event outside of <code>window</code> is to determine when a specific image has loaded.</p>
-
- <h4 id="jquery">jQuery</h4>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">$</span><span class="p">(</span><span class="s1">'img'</span><span class="p">).</span><span class="nx">load</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
- <span class="c1">// image has successfully loaded</span>
- <span class="p">});</span>
- </code></pre></div>
- <p>You can also determine if the image has failed to load:</p>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">$</span><span class="p">(</span><span class="s1">'img'</span><span class="p">).</span><span class="nx">error</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
- <span class="c1">// image has failed to load</span>
- <span class="p">});</span>
- </code></pre></div>
- <h4 id="web-api">Web API</h4>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">img</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">'load'</span><span class="p">,</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
- <span class="c1">// image has successfully loaded</span>
- <span class="p">});</span>
- </code></pre></div>
- <p>And if the image should fail to load?</p>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">img</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">'error'</span><span class="p">,</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
- <span class="c1">// image has failed to load</span>
- <span class="p">});</span>
- </code></pre></div>
- <p>As we've seen many times before, the syntax between jQuery and the Web API here for modern browsers is strikingly similar.</p>
-
- <h2 id="ancient-browser-support">Ancient Browser Support</h2>
-
- <p>This is where I talk about a time when jQuery was indeed a required library for web applications. Back when it was common to support IE8 or something even older. Back then, the Web/DOM API was a bit of a mess in some instances. This was especially true when dealing with events. Below, I'm going to briefly discuss some of the ways you can deal with events using vanilla JavaScript in older browsers. <strong>I'm going to limit this to IE7 and IE8.</strong> <a href="https://www.modern.ie/en-us/ie6countdown">IE6 is mostly dead at this point anyway</a>. Though many, if not all, of these examples should apply to IE6 as well.</p>
-
- <h3 id="listening-for-events">Listening For Events</h3>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">someElement</span><span class="p">.</span><span class="nx">attachEvent</span><span class="p">(</span><span class="s1">'onclick'</span><span class="p">,</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
- <span class="c1">// TODO event handler logic</span>
- <span class="p">});</span>
- </code></pre></div>
- <p>You'll notice two distinct differences between this and the modern browser approach.</p>
-
- <ol>
- <li>We must rely on <code>attachEvent</code> instead of <code>addEventListener</code>.</li>
- <li>The event name must include a prefix of "on".</li>
- </ol>
-
- <p>Maybe you're wondering how you can easily and programmatically use the correct event handling method, based on the browser's capabilities. For most of us developing apps exclusively for modern browsers, this isn't a concern. But if, for some reason, you must target ancient browsers, such as IE8 (or older), you can use the following code to register for an event in any browser:</p>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">function</span> <span class="nx">registerHandler</span><span class="p">(</span><span class="nx">target</span><span class="p">,</span> <span class="nx">type</span><span class="p">,</span> <span class="nx">callback</span><span class="p">)</span> <span class="p">{</span>
- <span class="kd">var</span> <span class="nx">listenerMethod</span> <span class="o">=</span> <span class="nx">target</span><span class="p">.</span><span class="nx">addEventListener</span> <span class="o">||</span> <span class="nx">target</span><span class="p">.</span><span class="nx">attachEvent</span><span class="p">,</span>
- <span class="nx">eventName</span> <span class="o">=</span> <span class="nx">target</span><span class="p">.</span><span class="nx">addEventListener</span> <span class="o">?</span> <span class="nx">type</span> <span class="o">:</span> <span class="s1">'on'</span> <span class="o">+</span> <span class="nx">type</span><span class="p">;</span>
-
- <span class="nx">listenerMethod</span><span class="p">(</span><span class="nx">eventName</span><span class="p">,</span> <span class="nx">callback</span><span class="p">);</span>
- <span class="p">}</span>
-
- <span class="c1">// example use</span>
- <span class="nx">registerHandler</span><span class="p">(</span><span class="nx">someElement</span><span class="p">,</span> <span class="s1">'click'</span><span class="p">,</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
- <span class="c1">// TODO event handler logic</span>
- <span class="p">});</span>
- </code></pre></div>
- <p>One more thing: if you want to remove an event handler in IE8 and older, you must use <code>detachEvent</code> instead of <code>removeEventListener</code>. So, a cross-browser way to remove an event listener may look like this:</p>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">function</span> <span class="nx">unregisterHandler</span><span class="p">(</span><span class="nx">target</span><span class="p">,</span> <span class="nx">type</span><span class="p">,</span> <span class="nx">callback</span><span class="p">)</span> <span class="p">{</span>
- <span class="kd">var</span> <span class="nx">removeMethod</span> <span class="o">=</span> <span class="nx">target</span><span class="p">.</span><span class="nx">removeEventListener</span> <span class="o">||</span> <span class="nx">target</span><span class="p">.</span><span class="nx">detachEvent</span><span class="p">,</span>
- <span class="nx">eventName</span> <span class="o">=</span> <span class="nx">target</span><span class="p">.</span><span class="nx">removeEventListener</span> <span class="o">?</span> <span class="nx">type</span> <span class="o">:</span> <span class="s1">'on'</span> <span class="o">+</span> <span class="nx">type</span><span class="p">;</span>
-
- <span class="nx">removeMethod</span><span class="p">(</span><span class="nx">eventName</span><span class="p">,</span> <span class="nx">callback</span><span class="p">);</span>
- <span class="p">}</span>
-
- <span class="c1">// example use</span>
- <span class="nx">unregisterHandler</span><span class="p">(</span><span class="nx">someElement</span><span class="p">,</span> <span class="s1">'click'</span><span class="p">,</span> <span class="nx">someEventHandlerFunction</span><span class="p">);</span>
- </code></pre></div>
- <h3 id="form-field-change-events">Form Field Change Events</h3>
-
- <p>Older versions of IE have some serious change-event deficiencies. Here are the two big ones that come to mind:</p>
-
- <ol>
- <li>Change events do not bubble.</li>
- <li>Checkboxes and radio buttons may not trigger a change event at all.</li>
- </ol>
-
- <p>It's important to know that the 2nd issue above was also reproducible when using jQuery with IE7/8 for quite a long time. As far as I can tell, current versions of jQuery (~1.10+) do properly address this issue though.</p>
-
- <p>To solve issue #1, you must attach a change handler directly to any form field that you'd like to monitor. Event delegation is not possible. For issue #2, you're best bet may be to attach a click handler to radio/checkbox fields instead of relying on the change event.</p>
-
- <h3 id="the-event-object">The Event Object</h3>
-
- <p>First off, in IE8 and older, the <code>Event</code> object is not passed directly to a registered event handler (remember, you must use <code>attachEvent</code>). Instead, the <code>Event</code> is set as a property on the <code>window</code>. So, if you are are writing an event handler that may be executed in modern <em>or</em> ancient browsers, you'll need something like this to cover both cases:</p>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">function</span> <span class="nx">myEventHandler</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
- <span class="kd">var</span> <span class="nx">actualEvent</span> <span class="o">=</span> <span class="nx">event</span> <span class="o">||</span> <span class="nb">window</span><span class="p">.</span><span class="nx">event</span><span class="p">;</span>
-
- <span class="c1">// handle actualEvent</span>
- <span class="p">}</span>
- </code></pre></div>
- <p>Also, some properties of the <code>Event</code> object instance are a bit different in older browsers. For example, while the target of the event in modern browsers can be found by checking the <code>target</code> property of the <code>Event</code> instance, IE8 and older contain a different property for this element, named <code>srcElement</code>. So, now your cross-browser event handler looks like this:</p>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">function</span> <span class="nx">myEventHandler</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
- <span class="kd">var</span> <span class="nx">actualEvent</span> <span class="o">=</span> <span class="nx">event</span> <span class="o">||</span> <span class="nb">window</span><span class="p">.</span><span class="nx">event</span><span class="p">,</span>
- <span class="nx">actualTarget</span> <span class="o">=</span> <span class="nx">actualEvent</span><span class="p">.</span><span class="nx">target</span> <span class="o">||</span> <span class="nx">actualEvent</span><span class="p">.</span><span class="nx">srcElement</span>
-
- <span class="c1">// handle actualEvent & actualTarget</span>
- <span class="p">}</span>
- </code></pre></div>
- <p>In terms of controlling your events, the <code>stopPropagation</code> method is not available on an <code>Event</code> object instance in IE8 and older. If you want to stop an event from bubbling, you must instead set the <code>cancelBubble</code> property on the event. A cross-browser solution would look like this:</p>
- <div class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">function</span> <span class="nx">myEventHandler</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
- <span class="kd">var</span> <span class="nx">actualEvent</span> <span class="o">=</span> <span class="nx">event</span> <span class="o">||</span> <span class="nb">window</span><span class="p">.</span><span class="nx">event</span><span class="p">;</span>
-
- <span class="k">if</span> <span class="p">(</span><span class="nx">actualEvent</span><span class="p">.</span><span class="nx">stopPropgation</span><span class="p">)</span> <span class="p">{</span>
- <span class="nx">actualEvent</span><span class="p">.</span><span class="nx">stopPropagation</span><span class="p">();</span>
- <span class="p">}</span>
- <span class="k">else</span> <span class="p">{</span>
- <span class="nx">actualEvent</span><span class="p">.</span><span class="nx">cancelBubble</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span>
- <span class="p">}</span>
- <span class="p">}</span>
- </code></pre></div>
- <p>IE8 and older also do not have a <code>stopImmediatePropagation</code> method. There isn't much to be done about this. I don't see lack of this method as a big loss, as use of <code>stopImmediatePropagation</code> seems like a code smell to me since the behavior of this call is completely dependent on the order that multiple event handlers are attached to the element in question.</p>
-
- <h3 id="browser-load-events">Browser Load Events</h3>
-
- <p>While <code>load</code> events on the <code>window</code> seem to function fairly well in ancient browsers, the <code>DOMContentLoaded</code> event was not supported by Internet Explorer until version 9. For older versions, the solution is a bit of a kludge. If <code>DOMContentLoaded</code> is really very important to you, and you must support IE8 and older, consider pulling in the tiny <a href="https://github.com/dperini/ContentLoaded/blob/master/src/contentloaded.js">contentloaded.js script</a>.</p>
-
- <p><a href="https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded#Cross-browser_fallback">Mozilla Developer Network provides a great explanation of the logic required to mimic the behavior of the <code>DOMContentLoaded</code> event in ancient browsers</a>:</p>
-
- <blockquote>
- <p>Internet Explorer 8 supports the readystatechange event, which can be used to detect when the DOM is ready. In earlier versions of Internet Explorer, this state can be detected by repeatedly trying to execute document.documentElement.doScroll("left");, as this snippet will throw an error until the DOM is ready.</p>
- </blockquote>
-
- <p>Of course, there are other gotchas in the context of event handling when dealing with ancient browsers. I've decided to outline a few of the more common ones above. If I forgot to mention something earth-shattering, please let me know in the comments.</p>
-
- <h2 id="libraries-to-consider">Libraries to Consider</h2>
-
- <p>You likely don't need a library to help you deal with events in modern browsers. But, if you really want some bells & whistles:</p>
-
- <ul>
- <li>Consider using <a href="https://github.com/fat/bean">bean</a> for dealing with various event-related tasks. Bean was written by one of the original developers of Bootstrap.</li>
- <li><a href="http://craig.is/killing/mice">Mousetrap</a> is a nifty little library that makes it simple and fun to handle various keyboard shortcuts.</li>
- <li><a href="https://github.com/mroderick/PubSubJS">PubSubJS</a> is a small library that, as the readme states, focuses on topic-based publish/subscribe support.</li>
- </ul>
-
- <h2 id="next">Next</h2>
-
- <p>For me: I'll talk about various utility functions and tasks that are commonly needed when developing most web applications. This will be more of a (but not entirely) JavaScript-as-a-language focus. By contrast, most of my previous posts have focused almost exclusively on the Web/DOM API.</p>
-
- <p>For you: if I've left out any important event-related topics, please let me know in the comments so I can update this post.</p>
-
- </div>
- </article>
- </section>
-
-
- <nav id="jumpto">
- <p>
- <a href="/david/blog/">Accueil du blog</a> |
- <a href="http://blog.garstasio.com/you-dont-need-jquery/events/">Source originale</a> |
- <a href="/david/stream/2019/">Accueil du flux</a>
- </p>
- </nav>
-
- <footer>
- <div>
- <img src="/static/david/david-larlet-avatar.jpg" loading="lazy" class="avatar" width="200" height="200">
- <p>
- Bonjour/Hi!
- Je suis <a href="/david/" title="Profil public">David Larlet</a>, je vis actuellement à Montréal et j’alimente cet espace depuis 15 ans. <br>
- Si tu as apprécié cette lecture, n’hésite pas à poursuivre ton exploration. Par exemple via les <a href="/david/blog/" title="Expériences bienveillantes">réflexions bimestrielles</a>, la <a href="/david/stream/2019/" title="Pensées (dés)articulées">veille hebdomadaire</a> ou en t’abonnant au <a href="/david/log/" title="S’abonner aux publications via RSS">flux RSS</a> (<a href="/david/blog/2019/flux-rss/" title="Tiens c’est quoi un flux RSS ?">so 2005</a>).
- </p>
- <p>
- Je m’intéresse à la place que je peux avoir dans ce monde. En tant qu’humain, en tant que membre d’une famille et en tant qu’associé d’une coopérative. De temps en temps, je fais aussi des <a href="https://github.com/davidbgk" title="Principalement sur Github mais aussi ailleurs">trucs techniques</a>. Et encore plus rarement, <a href="/david/talks/" title="En ce moment je laisse plutôt la place aux autres">j’en parle</a>.
- </p>
-
- <p>
- Voici quelques articles choisis :
- <a href="/david/blog/2019/faire-equipe/" title="Accéder à l’article complet">Faire équipe</a>,
- <a href="/david/blog/2018/bivouac-automnal/" title="Accéder à l’article complet">Bivouac automnal</a>,
- <a href="/david/blog/2018/commodite-effondrement/" title="Accéder à l’article complet">Commodité et effondrement</a>,
- <a href="/david/blog/2017/donnees-communs/" title="Accéder à l’article complet">Des données aux communs</a>,
- <a href="/david/blog/2016/accompagner-enfant/" title="Accéder à l’article complet">Accompagner un enfant</a>,
- <a href="/david/blog/2016/senior-developer/" title="Accéder à l’article complet">Senior developer</a>,
- <a href="/david/blog/2016/illusion-sociale/" title="Accéder à l’article complet">L’illusion sociale</a>,
- <a href="/david/blog/2016/instantane-scopyleft/" title="Accéder à l’article complet">Instantané Scopyleft</a>,
- <a href="/david/blog/2016/enseigner-web/" title="Accéder à l’article complet">Enseigner le Web</a>,
- <a href="/david/blog/2016/simplicite-defaut/" title="Accéder à l’article complet">Simplicité par défaut</a>,
- <a href="/david/blog/2016/minimalisme-esthetique/" title="Accéder à l’article complet">Minimalisme et esthétique</a>,
- <a href="/david/blog/2014/un-web-omni-present/" title="Accéder à l’article complet">Un web omni-présent</a>,
- <a href="/david/blog/2014/manifeste-developpeur/" title="Accéder à l’article complet">Manifeste de développeur</a>,
- <a href="/david/blog/2013/confort-convivialite/" title="Accéder à l’article complet">Confort et convivialité</a>,
- <a href="/david/blog/2013/testament-numerique/" title="Accéder à l’article complet">Testament numérique</a>,
- et <a href="/david/blog/" title="Accéder aux archives">bien d’autres…</a>
- </p>
- <p>
- On peut <a href="mailto:david%40larlet.fr" title="Envoyer un courriel">échanger par courriel</a>. Si éventuellement tu souhaites que l’on travaille ensemble, tu devrais commencer par consulter le <a href="http://larlet.com">profil dédié à mon activité professionnelle</a> et/ou contacter directement <a href="http://scopyleft.fr/">scopyleft</a>, la <abbr title="Société coopérative et participative">SCOP</abbr> dont je fais partie depuis six ans. Je recommande au préalable de lire <a href="/david/blog/2018/cout-site/" title="Attention ce qui va suivre peut vous choquer">combien coûte un site</a> et pourquoi je suis plutôt favorable à une <a href="/david/pro/devis/" title="Discutons-en !">non-demande de devis</a>.
- </p>
- <p>
- Je ne traque pas ta navigation mais mon
- <abbr title="Alwaysdata, 62 rue Tiquetonne 75002 Paris, +33.184162340">hébergeur</abbr>
- conserve des logs d’accès.
- </p>
- </div>
- </footer>
- <script type="text/javascript">
- ;(_ => {
- const jumper = document.getElementById('jumper')
- jumper.addEventListener('click', e => {
- e.preventDefault()
- const anchor = e.target.getAttribute('href')
- const targetEl = document.getElementById(anchor.substring(1))
- targetEl.scrollIntoView({behavior: 'smooth'})
- })
- })()
- </script>
|