A place to cache linked articles (think custom and personal wayback machine)
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  1. <!doctype html><!-- This is a valid HTML5 document. -->
  2. <!-- Screen readers, SEO, extensions and so on. -->
  3. <html lang=fr>
  4. <!-- Has to be within the first 1024 bytes, hence before the <title>
  5. See: https://www.w3.org/TR/2012/CR-html5-20121217/document-metadata.html#charset -->
  6. <meta charset=utf-8>
  7. <!-- Why no `X-UA-Compatible` meta: https://stackoverflow.com/a/6771584 -->
  8. <!-- The viewport meta is quite crowded and we are responsible for that.
  9. See: https://codepen.io/tigt/post/meta-viewport-for-2015 -->
  10. <meta name=viewport content="width=device-width,minimum-scale=1,initial-scale=1,shrink-to-fit=no">
  11. <!-- Required to make a valid HTML5 document. -->
  12. <title>You Don't Need jQuery! (archive) — David Larlet</title>
  13. <!-- Generated from https://realfavicongenerator.net/ such a mess. -->
  14. <link rel="apple-touch-icon" sizes="180x180" href="/static/david/icons/apple-touch-icon.png">
  15. <link rel="icon" type="image/png" sizes="32x32" href="/static/david/icons/favicon-32x32.png">
  16. <link rel="icon" type="image/png" sizes="16x16" href="/static/david/icons/favicon-16x16.png">
  17. <link rel="manifest" href="/manifest.json">
  18. <link rel="mask-icon" href="/static/david/icons/safari-pinned-tab.svg" color="#5bbad5">
  19. <link rel="shortcut icon" href="/static/david/icons/favicon.ico">
  20. <meta name="apple-mobile-web-app-title" content="David Larlet">
  21. <meta name="application-name" content="David Larlet">
  22. <meta name="msapplication-TileColor" content="#da532c">
  23. <meta name="msapplication-config" content="/static/david/icons/browserconfig.xml">
  24. <meta name="theme-color" content="#f0f0ea">
  25. <!-- That good ol' feed, subscribe :p. -->
  26. <link rel=alternate type="application/atom+xml" title=Feed href="/david/log/">
  27. <meta name="robots" content="noindex, nofollow">
  28. <meta content="origin-when-cross-origin" name="referrer">
  29. <!-- Canonical URL for SEO purposes -->
  30. <link rel="canonical" href="http://blog.garstasio.com/you-dont-need-jquery/events/">
  31. <style>
  32. /* http://meyerweb.com/eric/tools/css/reset/ */
  33. html, body, div, span,
  34. h1, h2, h3, h4, h5, h6, p, blockquote, pre,
  35. a, abbr, address, big, cite, code,
  36. del, dfn, em, img, ins,
  37. small, strike, strong, tt, var,
  38. dl, dt, dd, ol, ul, li,
  39. fieldset, form, label, legend,
  40. table, caption, tbody, tfoot, thead, tr, th, td,
  41. article, aside, canvas, details, embed,
  42. figure, figcaption, footer, header, hgroup,
  43. menu, nav, output, ruby, section, summary,
  44. time, mark, audio, video {
  45. margin: 0;
  46. padding: 0;
  47. border: 0;
  48. font-size: 100%;
  49. font: inherit;
  50. vertical-align: baseline;
  51. }
  52. /* HTML5 display-role reset for older browsers */
  53. article, aside, details, figcaption, figure,
  54. footer, header, hgroup, menu, nav, section { display: block; }
  55. body { line-height: 1; }
  56. blockquote, q { quotes: none; }
  57. blockquote:before, blockquote:after,
  58. q:before, q:after {
  59. content: '';
  60. content: none;
  61. }
  62. table {
  63. border-collapse: collapse;
  64. border-spacing: 0;
  65. }
  66. /* http://practicaltypography.com/equity.html */
  67. /* https://calendar.perfplanet.com/2016/no-font-face-bulletproof-syntax/ */
  68. /* https://www.filamentgroup.com/lab/js-web-fonts.html */
  69. @font-face {
  70. font-family: 'EquityTextB';
  71. src: url('/static/david/css/fonts/Equity-Text-B-Regular-webfont.woff2') format('woff2'),
  72. url('/static/david/css/fonts/Equity-Text-B-Regular-webfont.woff') format('woff');
  73. font-weight: 300;
  74. font-style: normal;
  75. font-display: swap;
  76. }
  77. @font-face {
  78. font-family: 'EquityTextB';
  79. src: url('/static/david/css/fonts/Equity-Text-B-Italic-webfont.woff2') format('woff2'),
  80. url('/static/david/css/fonts/Equity-Text-B-Italic-webfont.woff') format('woff');
  81. font-weight: 300;
  82. font-style: italic;
  83. font-display: swap;
  84. }
  85. @font-face {
  86. font-family: 'EquityTextB';
  87. src: url('/static/david/css/fonts/Equity-Text-B-Bold-webfont.woff2') format('woff2'),
  88. url('/static/david/css/fonts/Equity-Text-B-Bold-webfont.woff') format('woff');
  89. font-weight: 700;
  90. font-style: normal;
  91. font-display: swap;
  92. }
  93. @font-face {
  94. font-family: 'ConcourseT3';
  95. src: url('/static/david/css/fonts/concourse_t3_regular-webfont-20190806.woff2') format('woff2'),
  96. url('/static/david/css/fonts/concourse_t3_regular-webfont-20190806.woff') format('woff');
  97. font-weight: 300;
  98. font-style: normal;
  99. font-display: swap;
  100. }
  101. /* http://practice.typekit.com/lesson/caring-about-opentype-features/ */
  102. body {
  103. /* http://www.cssfontstack.com/ Palatino 99% Win 86% Mac */
  104. font-family: "EquityTextB", Palatino, serif;
  105. background-color: #f0f0ea;
  106. color: #07486c;
  107. font-kerning: normal;
  108. -moz-osx-font-smoothing: grayscale;
  109. -webkit-font-smoothing: subpixel-antialiased;
  110. text-rendering: optimizeLegibility;
  111. font-variant-ligatures: common-ligatures contextual;
  112. font-feature-settings: "kern", "liga", "clig", "calt";
  113. }
  114. pre, code, kbd, samp, var, tt {
  115. font-family: 'TriplicateT4c', monospace;
  116. }
  117. em {
  118. font-style: italic;
  119. color: #323a45;
  120. }
  121. strong {
  122. font-weight: bold;
  123. color: black;
  124. }
  125. nav {
  126. background-color: #323a45;
  127. color: #f0f0ea;
  128. display: flex;
  129. justify-content: space-around;
  130. padding: 1rem .5rem;
  131. }
  132. nav:last-child {
  133. border-bottom: 1vh solid #2d7474;
  134. }
  135. nav a {
  136. color: #f0f0ea;
  137. }
  138. nav abbr {
  139. border-bottom: 1px dotted white;
  140. }
  141. h1 {
  142. border-top: 1vh solid #2d7474;
  143. border-bottom: .2vh dotted #2d7474;
  144. background-color: #e3e1e1;
  145. color: #323a45;
  146. text-align: center;
  147. padding: 5rem 0 4rem 0;
  148. width: 100%;
  149. font-family: 'ConcourseT3';
  150. display: flex;
  151. flex-direction: column;
  152. }
  153. h1.single {
  154. padding-bottom: 10rem;
  155. }
  156. h1 span {
  157. position: absolute;
  158. top: 1vh;
  159. left: 20%;
  160. line-height: 0;
  161. }
  162. h1 span a {
  163. line-height: 1.7;
  164. padding: 1rem 1.2rem .6rem 1.2rem;
  165. border-radius: 0 0 6% 6%;
  166. background: #2d7474;
  167. font-size: 1.3rem;
  168. color: white;
  169. text-decoration: none;
  170. }
  171. h2 {
  172. margin: 4rem 0 1rem;
  173. border-top: .2vh solid #2d7474;
  174. padding-top: 1vh;
  175. }
  176. h3 {
  177. text-align: center;
  178. margin: 3rem 0 .75em;
  179. }
  180. hr {
  181. height: .4rem;
  182. width: .4rem;
  183. border-radius: .4rem;
  184. background: #07486c;
  185. margin: 2.5rem auto;
  186. }
  187. time {
  188. display: bloc;
  189. margin-left: 0 !important;
  190. }
  191. ul, ol {
  192. margin: 2rem;
  193. }
  194. ul {
  195. list-style-type: square;
  196. }
  197. a {
  198. text-decoration-skip-ink: auto;
  199. text-decoration-thickness: 0.05em;
  200. text-underline-offset: 0.09em;
  201. }
  202. article {
  203. max-width: 50rem;
  204. display: flex;
  205. flex-direction: column;
  206. margin: 2rem auto;
  207. }
  208. article.single {
  209. border-top: .2vh dotted #2d7474;
  210. margin: -6rem auto 1rem auto;
  211. background: #f0f0ea;
  212. padding: 2rem;
  213. }
  214. article p:last-child {
  215. margin-bottom: 1rem;
  216. }
  217. p {
  218. padding: 0 .5rem;
  219. margin-left: 3rem;
  220. }
  221. p + p,
  222. figure + p {
  223. margin-top: 2rem;
  224. }
  225. blockquote {
  226. background-color: #e3e1e1;
  227. border-left: .5vw solid #2d7474;
  228. display: flex;
  229. flex-direction: column;
  230. align-items: center;
  231. padding: 1rem;
  232. margin: 1.5rem;
  233. }
  234. blockquote cite {
  235. font-style: italic;
  236. }
  237. blockquote p {
  238. margin-left: 0;
  239. }
  240. figure {
  241. border-top: .2vh solid #2d7474;
  242. background-color: #e3e1e1;
  243. text-align: center;
  244. padding: 1.5rem 0;
  245. margin: 1rem 0 0;
  246. font-size: 1.5rem;
  247. width: 100%;
  248. }
  249. figure img {
  250. max-width: 250px;
  251. max-height: 250px;
  252. border: .5vw solid #323a45;
  253. padding: 1px;
  254. }
  255. figcaption {
  256. padding: 1rem;
  257. line-height: 1.4;
  258. }
  259. aside {
  260. display: flex;
  261. flex-direction: column;
  262. background-color: #e3e1e1;
  263. padding: 1rem 0;
  264. border-bottom: .2vh solid #07486c;
  265. }
  266. aside p {
  267. max-width: 50rem;
  268. margin: 0 auto;
  269. }
  270. /* https://fvsch.com/code/css-locks/ */
  271. p, li, pre, code, kbd, samp, var, tt, time, details, figcaption {
  272. font-size: 1rem;
  273. line-height: calc( 1.5em + 0.2 * 1rem );
  274. }
  275. h1 {
  276. font-size: 1.9rem;
  277. line-height: calc( 1.2em + 0.2 * 1rem );
  278. }
  279. h2 {
  280. font-size: 1.6rem;
  281. line-height: calc( 1.3em + 0.2 * 1rem );
  282. }
  283. h3 {
  284. font-size: 1.35rem;
  285. line-height: calc( 1.4em + 0.2 * 1rem );
  286. }
  287. @media (min-width: 20em) {
  288. /* The (100vw - 20rem) / (50 - 20) part
  289. resolves to 0-1rem, depending on the
  290. viewport width (between 20em and 50em). */
  291. p, li, pre, code, kbd, samp, var, tt, time, details, figcaption {
  292. font-size: calc( 1rem + .6 * (100vw - 20rem) / (50 - 20) );
  293. line-height: calc( 1.5em + 0.2 * (100vw - 50rem) / (20 - 50) );
  294. margin-left: 0;
  295. }
  296. h1 {
  297. font-size: calc( 1.9rem + 1.5 * (100vw - 20rem) / (50 - 20) );
  298. line-height: calc( 1.2em + 0.2 * (100vw - 50rem) / (20 - 50) );
  299. }
  300. h2 {
  301. font-size: calc( 1.5rem + 1.5 * (100vw - 20rem) / (50 - 20) );
  302. line-height: calc( 1.3em + 0.2 * (100vw - 50rem) / (20 - 50) );
  303. }
  304. h3 {
  305. font-size: calc( 1.35rem + 1.5 * (100vw - 20rem) / (50 - 20) );
  306. line-height: calc( 1.4em + 0.2 * (100vw - 50rem) / (20 - 50) );
  307. }
  308. }
  309. @media (min-width: 50em) {
  310. /* The right part of the addition *must* be a
  311. rem value. In this example we *could* change
  312. the whole declaration to font-size:2.5rem,
  313. but if our baseline value was not expressed
  314. in rem we would have to use calc. */
  315. p, li, pre, code, kbd, samp, var, tt, time, details, figcaption {
  316. font-size: calc( 1rem + .6 * 1rem );
  317. line-height: 1.5em;
  318. }
  319. p, li, pre, details {
  320. margin-left: 3rem;
  321. }
  322. h1 {
  323. font-size: calc( 1.9rem + 1.5 * 1rem );
  324. line-height: 1.2em;
  325. }
  326. h2 {
  327. font-size: calc( 1.5rem + 1.5 * 1rem );
  328. line-height: 1.3em;
  329. }
  330. h3 {
  331. font-size: calc( 1.35rem + 1.5 * 1rem );
  332. line-height: 1.4em;
  333. }
  334. figure img {
  335. max-width: 500px;
  336. max-height: 500px;
  337. }
  338. }
  339. figure.unsquared {
  340. margin-bottom: 1.5rem;
  341. }
  342. figure.unsquared img {
  343. height: inherit;
  344. }
  345. @media print {
  346. body { font-size: 100%; }
  347. a:after { content: " (" attr(href) ")"; }
  348. a, a:link, a:visited, a:after {
  349. text-decoration: underline;
  350. text-shadow: none !important;
  351. background-image: none !important;
  352. background: white;
  353. color: black;
  354. }
  355. abbr[title] { border-bottom: 0; }
  356. abbr[title]:after { content: " (" attr(title) ")"; }
  357. img { page-break-inside: avoid; }
  358. @page { margin: 2cm .5cm; }
  359. h1, h2, h3 { page-break-after: avoid; }
  360. p3 { orphans: 3; widows: 3; }
  361. img {
  362. max-width: 250px !important;
  363. max-height: 250px !important;
  364. }
  365. nav, aside { display: none; }
  366. }
  367. ul.with_columns {
  368. column-count: 1;
  369. }
  370. @media (min-width: 20em) {
  371. ul.with_columns {
  372. column-count: 2;
  373. }
  374. }
  375. @media (min-width: 50em) {
  376. ul.with_columns {
  377. column-count: 3;
  378. }
  379. }
  380. ul.with_two_columns {
  381. column-count: 1;
  382. }
  383. @media (min-width: 20em) {
  384. ul.with_two_columns {
  385. column-count: 1;
  386. }
  387. }
  388. @media (min-width: 50em) {
  389. ul.with_two_columns {
  390. column-count: 2;
  391. }
  392. }
  393. .gallery {
  394. display: flex;
  395. flex-wrap: wrap;
  396. justify-content: space-around;
  397. }
  398. .gallery figure img {
  399. margin-left: 1rem;
  400. margin-right: 1rem;
  401. }
  402. .gallery figure figcaption {
  403. font-family: 'ConcourseT3'
  404. }
  405. footer {
  406. font-family: 'ConcourseT3';
  407. display: flex;
  408. flex-direction: column;
  409. border-top: 3px solid white;
  410. padding: 4rem 0;
  411. background-color: #07486c;
  412. color: white;
  413. }
  414. footer > * {
  415. max-width: 50rem;
  416. margin: 0 auto;
  417. }
  418. footer a {
  419. color: #f1c40f;
  420. }
  421. footer .avatar {
  422. width: 200px;
  423. height: 200px;
  424. border-radius: 50%;
  425. float: left;
  426. -webkit-shape-outside: circle();
  427. shape-outside: circle();
  428. margin-right: 2rem;
  429. padding: 2px 5px 5px 2px;
  430. background: white;
  431. border-left: 1px solid #f1c40f;
  432. border-top: 1px solid #f1c40f;
  433. border-right: 5px solid #f1c40f;
  434. border-bottom: 5px solid #f1c40f;
  435. }
  436. </style>
  437. <h1>
  438. <span><a id="jumper" href="#jumpto" title="Un peu perdu ?">?</a></span>
  439. You Don't Need jQuery! (archive)
  440. <time>Pour la pérennité des contenus liés. Non-indexé, retrait sur simple email.</time>
  441. </h1>
  442. <section>
  443. <article>
  444. <h3><a href="http://blog.garstasio.com/you-dont-need-jquery/events/">Source originale du contenu</a></h3>
  445. <div class="entry">
  446. <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>
  447. <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>
  448. <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>
  449. <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>
  450. <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>
  451. <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>
  452. <ol>
  453. <li><a href="#sending-native-(dom)-events">Sending Native (DOM) Events</a></li>
  454. <li><a href="#sending-custom-events">Sending Custom Events</a></li>
  455. <li><a href="#listening-for-events">Listening For Events</a></li>
  456. <li><a href="#removing-event-handlers">Removing Event Handlers</a></li>
  457. <li><a href="#modifying-events">Modifying Events</a></li>
  458. <li><a href="#event-delgation">Event Delegation</a></li>
  459. <li><a href="#keyboard-events">Keyboard Events</a></li>
  460. <li><a href="#mouse-events">Mouse Events</a></li>
  461. <li><a href="#browser-load-events">Browser Load Events</a></li>
  462. <li><a href="#ancient-browser-support">Ancient Browser Support</a></li>
  463. <li><a href="#libraries-to-consider">Libraries to Consider</a></li>
  464. <li><a href="#next">Next in this Series</a></li>
  465. </ol>
  466. <h2 id="sending-native-(dom)-events">Sending Native (DOM) Events</h2>
  467. <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>
  468. <p>Let's say we have an anchor tag, and we want to programmatically click it using JavaScript.</p>
  469. <h4 id="jquery">jQuery</h4>
  470. <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>
  471. </code></pre></div>
  472. <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>
  473. <h4 id="web-api">Web API</h4>
  474. <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>&lt;form&gt;</code>.</p>
  475. <h2 id="sending-custom-events">Sending Custom Events</h2>
  476. <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>
  477. <h4 id="jquery">jQuery</h4>
  478. <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>
  479. </code></pre></div>
  480. <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>
  481. <h4 id="web-api">Web API</h4>
  482. <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>
  483. <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>
  484. <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>
  485. </code></pre></div>
  486. <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>
  487. <p>The more "modern" approach involves using the <code>CustomEvent</code> constructor:</p>
  488. <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>
  489. <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>
  490. </code></pre></div>
  491. <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>
  492. <h2 id="listening-for-events">Listening For Events</h2>
  493. <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>
  494. <h4 id="jquery">jQuery</h4>
  495. <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>
  496. <span class="c1">// TODO event handler logic</span>
  497. <span class="p">});</span>
  498. </code></pre></div>
  499. <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>
  500. <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>
  501. <span class="c1">// TODO event handler logic</span>
  502. <span class="p">});</span>
  503. </code></pre></div>
  504. <h4 id="web-api">Web API</h4>
  505. <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>
  506. <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>
  507. <span class="c1">// TODO event handler logic</span>
  508. <span class="p">});</span>
  509. </code></pre></div>
  510. <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>
  511. <h2 id="removing-event-handlers">Removing Event Handlers</h2>
  512. <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>
  513. <p>So, let's say we've previously attached the following click event handler to an element:</p>
  514. <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>
  515. <span class="c1">// handles the event...</span>
  516. <span class="p">}</span>
  517. </code></pre></div>
  518. <p>...and we now want to remove it:</p>
  519. <h4 id="jquery">jQuery</h4>
  520. <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>
  521. </code></pre></div>
  522. <h4 id="web-api">Web API</h4>
  523. <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>
  524. </code></pre></div>
  525. <h2 id="modifying-events">Modifying Events</h2>
  526. <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>
  527. <h3 id="preventing-the-event-from-bubbling-further-up-the-dom">Preventing the event from bubbling further up the DOM</h3>
  528. <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>
  529. <h4 id="jquery">jQuery</h4>
  530. <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>
  531. <span class="nx">event</span><span class="p">.</span><span class="nx">stopPropagation</span><span class="p">();</span>
  532. <span class="p">});</span>
  533. </code></pre></div>
  534. <h4 id="web-api">Web API</h4>
  535. <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>
  536. <span class="nx">event</span><span class="p">.</span><span class="nx">stopPropagation</span><span class="p">();</span>
  537. <span class="p">});</span>
  538. </code></pre></div>
  539. <p>The syntax between jQuery and the modern Web API here is almost identical.</p>
  540. <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>
  541. <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>
  542. <h4 id="jquery">jQuery</h4>
  543. <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>
  544. <span class="nx">event</span><span class="p">.</span><span class="nx">stopImmediatePropagation</span><span class="p">();</span>
  545. <span class="p">});</span>
  546. </code></pre></div>
  547. <h4 id="web-api">Web API</h4>
  548. <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>
  549. <span class="nx">event</span><span class="p">.</span><span class="nx">stopImmediatePropagation</span><span class="p">();</span>
  550. <span class="p">});</span>
  551. </code></pre></div>
  552. <p>Again, the syntax between jQuery and the modern Web API here is eerily similar.</p>
  553. <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>
  554. <p>Let's say we have the following element:</p>
  555. <div class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;a</span> <span class="na">href=</span><span class="s">"http://fineuploader.com"</span><span class="nt">&gt;</span>Go to Fine Uploader<span class="nt">&lt;/a&gt;</span>
  556. </code></pre></div>
  557. <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>
  558. <h4 id="jquery">jQuery</h4>
  559. <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>
  560. <span class="nx">event</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span>
  561. <span class="p">});</span>
  562. </code></pre></div>
  563. <h4 id="web-api">Web API</h4>
  564. <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>
  565. <span class="nx">event</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span>
  566. <span class="p">});</span>
  567. </code></pre></div>
  568. <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>
  569. <h2 id="event-delegation">Event Delegation</h2>
  570. <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>
  571. <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>
  572. <p>The markup for such a list may look like this:</p>
  573. <div class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;ul</span> <span class="na">id=</span><span class="s">"my-list"</span><span class="nt">&gt;</span>
  574. <span class="nt">&lt;li&gt;</span>foo <span class="nt">&lt;button&gt;</span>x<span class="nt">&lt;/button&gt;&lt;/li&gt;</span>
  575. <span class="nt">&lt;li&gt;</span>bar <span class="nt">&lt;button&gt;</span>x<span class="nt">&lt;/button&gt;&lt;/li&gt;</span>
  576. <span class="nt">&lt;li&gt;</span>abc <span class="nt">&lt;button&gt;</span>x<span class="nt">&lt;/button&gt;&lt;/li&gt;</span>
  577. <span class="nt">&lt;li&gt;</span>123 <span class="nt">&lt;button&gt;</span>x<span class="nt">&lt;/button&gt;&lt;/li&gt;</span>
  578. <span class="nt">&lt;/ul&gt;</span>
  579. </code></pre></div>
  580. <p>If the user clicks on the "x" button, the list item should be removed from the list.</p>
  581. <h4 id="jquery">jQuery</h4>
  582. <p>jQuery will set the context of our handler to the element that initially received the click (the <code>&lt;button&gt;</code>). Also, only <code>&lt;button&gt;</code> elements inside this list will be examined.</p>
  583. <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>
  584. <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>
  585. <span class="p">});</span>
  586. </code></pre></div>
  587. <h4 id="web-api">Web API</h4>
  588. <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>&lt;button&gt;</code> clicks.</p>
  589. <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>
  590. <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>
  591. <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>
  592. <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>
  593. <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>
  594. <span class="p">}</span>
  595. <span class="p">});</span>
  596. </code></pre></div>
  597. <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>
  598. <h2 id="keyboard-events">Keyboard Events</h2>
  599. <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>
  600. <p>First, we should take a moment to be sure we understand the difference between the three different types of general keyboard events:</p>
  601. <ol>
  602. <li><code>keydown</code>: Key has been pressed but not yet released. No default action has been performed yet.</li>
  603. <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>
  604. <li><code>keyup</code>: Pressed key has been released.</li>
  605. </ol>
  606. <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>
  607. <h4 id="jquery">jQuery</h4>
  608. <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>
  609. <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">&amp;&amp;</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>
  610. <span class="c1">// open help widget</span>
  611. <span class="p">}</span>
  612. <span class="p">});</span>
  613. </code></pre></div>
  614. <h4 id="web-api">Web API</h4>
  615. <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>
  616. <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">&amp;&amp;</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>
  617. <span class="c1">// open help widget</span>
  618. <span class="p">}</span>
  619. <span class="p">});</span>
  620. </code></pre></div>
  621. <p>Nothing is obviously gained, in this instance, with jQuery. Even the syntax is almost identical between the Web API and jQuery.</p>
  622. <p>Registering for other keyboard events follows a similar pattern:</p>
  623. <h4 id="jquery">jQuery</h4>
  624. <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>
  625. <span class="c1">// ...</span>
  626. <span class="p">});</span>
  627. <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>
  628. <span class="c1">// ...</span>
  629. <span class="p">});</span>
  630. </code></pre></div>
  631. <h4 id="web-api">Web API</h4>
  632. <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>
  633. <span class="c1">// ...</span>
  634. <span class="p">});</span>
  635. <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>
  636. <span class="c1">// ...</span>
  637. <span class="p">});</span>
  638. </code></pre></div>
  639. <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>
  640. <h2 id="mouse-events">Mouse Events</h2>
  641. <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>
  642. <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>
  643. <h3 id="jquery's-hover-event">jQuery's <code>hover</code> event</h3>
  644. <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>
  645. <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>
  646. <span class="kd">function</span> <span class="nx">hoverIn</span><span class="p">()</span> <span class="p">{</span>
  647. <span class="c1">// mouse is hovering over this element</span>
  648. <span class="p">},</span>
  649. <span class="kd">function</span> <span class="nx">hoverOut</span><span class="p">()</span> <span class="p">{</span>
  650. <span class="c1">// mouse was hovering over this element, but no longer is</span>
  651. <span class="p">}</span>
  652. <span class="p">);</span>
  653. </code></pre></div>
  654. <p>We can do the same thing with the Web API pretty easily:</p>
  655. <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>
  656. <span class="c1">// mouse is hovering over this element</span>
  657. <span class="p">});</span>
  658. <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>
  659. <span class="c1">// mouse was hovering over this element, but no longer is</span>
  660. <span class="p">});</span>
  661. </code></pre></div>
  662. <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>
  663. <h2 id="browser-load-events">Browser Load Events</h2>
  664. <p>When talking about "load" events in the browser, we may be trying to answer any one of the following questions:</p>
  665. <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>
  666. <p>This event should be fired after:</p>
  667. <ul>
  668. <li>all markup has been placed on the page</li>
  669. <li>all stylesheets have been loaded</li>
  670. <li>all images have loaded</li>
  671. <li>all iframes have fully loaded</li>
  672. </ul>
  673. <h4 id="jquery">jQuery</h4>
  674. <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>
  675. <span class="c1">// page is fully rendered</span>
  676. <span class="p">})</span>
  677. </code></pre></div>
  678. <h4 id="web-api">Web API</h4>
  679. <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>
  680. <span class="c1">// page is fully rendered</span>
  681. <span class="p">});</span>
  682. </code></pre></div>
  683. <h3 id="when-has-all-static-markup-been-placed-on-the-page?">When has all static markup been placed on the page?</h3>
  684. <p>This event should fire after all markup has been placed on the page.</p>
  685. <h4 id="jquery">jQuery</h4>
  686. <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>
  687. <span class="c1">// markup is on the page</span>
  688. <span class="p">});</span>
  689. </code></pre></div>
  690. <p>Note that you can also achieve the same thing in jQuery this way:</p>
  691. <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>
  692. <span class="c1">// markup is on the page</span>
  693. <span class="p">});</span>
  694. </code></pre></div>
  695. <h4 id="web-api">Web API</h4>
  696. <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>
  697. <span class="c1">// markup is on the page</span>
  698. <span class="p">});</span>
  699. </code></pre></div>
  700. <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>&lt;link&gt;</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>
  701. <h3 id="when-has-a-particular-element-on-the-page-fully-loaded?">When has a particular element on the page fully loaded?</h3>
  702. <p>In addition to <code>window</code>, load events are associated with a number of elements, such as <code>&lt;img&gt;</code>, <code>&lt;link&gt;</code>, and <code>&lt;script&gt;</code>. The most common use of this event outside of <code>window</code> is to determine when a specific image has loaded.</p>
  703. <h4 id="jquery">jQuery</h4>
  704. <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>
  705. <span class="c1">// image has successfully loaded</span>
  706. <span class="p">});</span>
  707. </code></pre></div>
  708. <p>You can also determine if the image has failed to load:</p>
  709. <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>
  710. <span class="c1">// image has failed to load</span>
  711. <span class="p">});</span>
  712. </code></pre></div>
  713. <h4 id="web-api">Web API</h4>
  714. <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>
  715. <span class="c1">// image has successfully loaded</span>
  716. <span class="p">});</span>
  717. </code></pre></div>
  718. <p>And if the image should fail to load?</p>
  719. <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>
  720. <span class="c1">// image has failed to load</span>
  721. <span class="p">});</span>
  722. </code></pre></div>
  723. <p>As we've seen many times before, the syntax between jQuery and the Web API here for modern browsers is strikingly similar.</p>
  724. <h2 id="ancient-browser-support">Ancient Browser Support</h2>
  725. <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>
  726. <h3 id="listening-for-events">Listening For Events</h3>
  727. <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>
  728. <span class="c1">// TODO event handler logic</span>
  729. <span class="p">});</span>
  730. </code></pre></div>
  731. <p>You'll notice two distinct differences between this and the modern browser approach.</p>
  732. <ol>
  733. <li>We must rely on <code>attachEvent</code> instead of <code>addEventListener</code>.</li>
  734. <li>The event name must include a prefix of "on".</li>
  735. </ol>
  736. <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>
  737. <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>
  738. <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>
  739. <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>
  740. <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>
  741. <span class="p">}</span>
  742. <span class="c1">// example use</span>
  743. <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>
  744. <span class="c1">// TODO event handler logic</span>
  745. <span class="p">});</span>
  746. </code></pre></div>
  747. <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>
  748. <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>
  749. <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>
  750. <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>
  751. <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>
  752. <span class="p">}</span>
  753. <span class="c1">// example use</span>
  754. <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>
  755. </code></pre></div>
  756. <h3 id="form-field-change-events">Form Field Change Events</h3>
  757. <p>Older versions of IE have some serious change-event deficiencies. Here are the two big ones that come to mind:</p>
  758. <ol>
  759. <li>Change events do not bubble.</li>
  760. <li>Checkboxes and radio buttons may not trigger a change event at all.</li>
  761. </ol>
  762. <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>
  763. <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>
  764. <h3 id="the-event-object">The Event Object</h3>
  765. <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>
  766. <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>
  767. <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>
  768. <span class="c1">// handle actualEvent</span>
  769. <span class="p">}</span>
  770. </code></pre></div>
  771. <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>
  772. <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>
  773. <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>
  774. <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>
  775. <span class="c1">// handle actualEvent &amp; actualTarget</span>
  776. <span class="p">}</span>
  777. </code></pre></div>
  778. <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>
  779. <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>
  780. <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>
  781. <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>
  782. <span class="nx">actualEvent</span><span class="p">.</span><span class="nx">stopPropagation</span><span class="p">();</span>
  783. <span class="p">}</span>
  784. <span class="k">else</span> <span class="p">{</span>
  785. <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>
  786. <span class="p">}</span>
  787. <span class="p">}</span>
  788. </code></pre></div>
  789. <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>
  790. <h3 id="browser-load-events">Browser Load Events</h3>
  791. <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>
  792. <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>
  793. <blockquote>
  794. <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>
  795. </blockquote>
  796. <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>
  797. <h2 id="libraries-to-consider">Libraries to Consider</h2>
  798. <p>You likely don't need a library to help you deal with events in modern browsers. But, if you really want some bells &amp; whistles:</p>
  799. <ul>
  800. <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>
  801. <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>
  802. <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>
  803. </ul>
  804. <h2 id="next">Next</h2>
  805. <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>
  806. <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>
  807. </div>
  808. </article>
  809. </section>
  810. <nav id="jumpto">
  811. <p>
  812. <a href="/david/blog/">Accueil du blog</a> |
  813. <a href="http://blog.garstasio.com/you-dont-need-jquery/events/">Source originale</a> |
  814. <a href="/david/stream/2019/">Accueil du flux</a>
  815. </p>
  816. </nav>
  817. <footer>
  818. <div>
  819. <img src="/static/david/david-larlet-avatar.jpg" loading="lazy" class="avatar" width="200" height="200">
  820. <p>
  821. Bonjour/Hi!
  822. Je suis <a href="/david/" title="Profil public">David&nbsp;Larlet</a>, je vis actuellement à Montréal et j’alimente cet espace depuis 15 ans. <br>
  823. 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>).
  824. </p>
  825. <p>
  826. 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>.
  827. </p>
  828. <p>
  829. Voici quelques articles choisis :
  830. <a href="/david/blog/2019/faire-equipe/" title="Accéder à l’article complet">Faire équipe</a>,
  831. <a href="/david/blog/2018/bivouac-automnal/" title="Accéder à l’article complet">Bivouac automnal</a>,
  832. <a href="/david/blog/2018/commodite-effondrement/" title="Accéder à l’article complet">Commodité et effondrement</a>,
  833. <a href="/david/blog/2017/donnees-communs/" title="Accéder à l’article complet">Des données aux communs</a>,
  834. <a href="/david/blog/2016/accompagner-enfant/" title="Accéder à l’article complet">Accompagner un enfant</a>,
  835. <a href="/david/blog/2016/senior-developer/" title="Accéder à l’article complet">Senior developer</a>,
  836. <a href="/david/blog/2016/illusion-sociale/" title="Accéder à l’article complet">L’illusion sociale</a>,
  837. <a href="/david/blog/2016/instantane-scopyleft/" title="Accéder à l’article complet">Instantané Scopyleft</a>,
  838. <a href="/david/blog/2016/enseigner-web/" title="Accéder à l’article complet">Enseigner le Web</a>,
  839. <a href="/david/blog/2016/simplicite-defaut/" title="Accéder à l’article complet">Simplicité par défaut</a>,
  840. <a href="/david/blog/2016/minimalisme-esthetique/" title="Accéder à l’article complet">Minimalisme et esthétique</a>,
  841. <a href="/david/blog/2014/un-web-omni-present/" title="Accéder à l’article complet">Un web omni-présent</a>,
  842. <a href="/david/blog/2014/manifeste-developpeur/" title="Accéder à l’article complet">Manifeste de développeur</a>,
  843. <a href="/david/blog/2013/confort-convivialite/" title="Accéder à l’article complet">Confort et convivialité</a>,
  844. <a href="/david/blog/2013/testament-numerique/" title="Accéder à l’article complet">Testament numérique</a>,
  845. et <a href="/david/blog/" title="Accéder aux archives">bien d’autres…</a>
  846. </p>
  847. <p>
  848. 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>.
  849. </p>
  850. <p>
  851. Je ne traque pas ta navigation mais mon
  852. <abbr title="Alwaysdata, 62 rue Tiquetonne 75002 Paris, +33.184162340">hébergeur</abbr>
  853. conserve des logs d’accès.
  854. </p>
  855. </div>
  856. </footer>
  857. <script type="text/javascript">
  858. ;(_ => {
  859. const jumper = document.getElementById('jumper')
  860. jumper.addEventListener('click', e => {
  861. e.preventDefault()
  862. const anchor = e.target.getAttribute('href')
  863. const targetEl = document.getElementById(anchor.substring(1))
  864. targetEl.scrollIntoView({behavior: 'smooth'})
  865. })
  866. })()
  867. </script>