{"id":382,"date":"2018-06-16T23:17:36","date_gmt":"2018-06-16T23:17:36","guid":{"rendered":"https:\/\/blog.hassler.ec\/wp\/?p=382"},"modified":"2018-06-16T23:17:36","modified_gmt":"2018-06-16T23:17:36","slug":"how-to-handle-event-handling-in-javascript-examples-and-all","status":"publish","type":"post","link":"https:\/\/blog.hassler.ec\/wp\/2018\/06\/16\/how-to-handle-event-handling-in-javascript-examples-and-all\/","title":{"rendered":"How to handle event handling in JavaScript (examples and\u00a0all)"},"content":{"rendered":"<div class=\"section-inner sectionLayout--insetColumn\">\n<figure id=\"511a\" class=\"graf graf--figure graf-after--h3\">\n<div class=\"aspectRatioPlaceholder is-locked\">\n<div class=\"aspectRatioPlaceholder-fill\"><\/div>\n<div class=\"progressiveMedia js-progressiveMedia graf-image is-canvasLoaded is-imageLoaded\" data-image-id=\"1*dhtbZon7OPebZuUO9-yyjw.jpeg\" data-width=\"4272\" data-height=\"2848\" data-is-featured=\"true\" data-action=\"zoom\" data-action-value=\"1*dhtbZon7OPebZuUO9-yyjw.jpeg\" data-scroll=\"native\"><canvas class=\"progressiveMedia-canvas js-progressiveMedia-canvas\" width=\"75\" height=\"50\"><\/canvas><img decoding=\"async\" class=\"progressiveMedia-image js-progressiveMedia-image\" src=\"https:\/\/cdn-images-1.medium.com\/max\/800\/1*dhtbZon7OPebZuUO9-yyjw.jpeg\" data-src=\"https:\/\/cdn-images-1.medium.com\/max\/800\/1*dhtbZon7OPebZuUO9-yyjw.jpeg\" \/><\/div>\n<\/div><figcaption class=\"imageCaption\">Photo by\u00a0<a class=\"markup--anchor markup--figure-anchor\" href=\"https:\/\/unsplash.com\/photos\/_UeY8aTI6d0?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText\" target=\"_blank\" rel=\"noopener\" data-href=\"https:\/\/unsplash.com\/photos\/_UeY8aTI6d0?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText\">Sergey Zolkin<\/a>\u00a0on\u00a0<a class=\"markup--anchor markup--figure-anchor\" href=\"https:\/\/unsplash.com\/search\/photos\/computer?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText\" target=\"_blank\" rel=\"noopener\" data-href=\"https:\/\/unsplash.com\/search\/photos\/computer?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText\">Unsplash<\/a><\/figcaption><\/figure>\n<p id=\"fa21\" class=\"graf graf--p graf-after--figure\">In this blog, I will try to make clear the fundamentals of the event handling mechanism in JavaScript, without the help of any external library like Jquery\/React\/Vue.<\/p>\n<p id=\"e18f\" class=\"graf graf--p graf-after--p\">I will be explaining the following topics in this article:<\/p>\n<ol class=\"postList\">\n<li id=\"80ef\" class=\"graf graf--li graf-after--p\">The<strong class=\"markup--strong markup--li-strong\">\u00a0document<\/strong>\u00a0and\u00a0<strong class=\"markup--strong markup--li-strong\">window<\/strong>\u00a0objects, and adding\u00a0<strong class=\"markup--strong markup--li-strong\">Event Listeners\u00a0<\/strong>to them.<\/li>\n<li id=\"fbfe\" class=\"graf graf--li graf-after--li\">The<strong class=\"markup--strong markup--li-strong\">\u00a0Event.preventDefault()<\/strong>\u00a0method and it\u2019s usage.<\/li>\n<li id=\"42e7\" class=\"graf graf--li graf-after--li\">The<strong class=\"markup--strong markup--li-strong\">\u00a0Event.stopPropagation()\u00a0<\/strong>method with an example.<\/li>\n<li id=\"7f4a\" class=\"graf graf--li graf-after--li\"><strong class=\"markup--strong markup--li-strong\">How to remove\u00a0<\/strong>an event\u00a0<strong class=\"markup--strong markup--li-strong\">listener<\/strong>\u00a0from an element.<\/li>\n<\/ol>\n<h3 id=\"5568\" class=\"graf graf--h3 graf-after--li\"><strong class=\"markup--strong markup--h3-strong\">Document<\/strong>\u00a0and\u00a0<strong class=\"markup--strong markup--h3-strong\">window\u00a0<\/strong>objects with\u00a0<strong class=\"markup--strong markup--h3-strong\">Event Listeners<\/strong><\/h3>\n<p id=\"224f\" class=\"graf graf--p graf-after--h3\">The Window object represents the tab. In case you are reading this blog on your corresponding browser, then your current tab represents the Window object.<\/p>\n<p id=\"5bf8\" class=\"graf graf--p graf-after--p\">The window object has access to such information as the toolbar, height and width of the window, prompts, and alerts. Let\u2019s see how we can add an event listener (mousedown) to the window object and analyze some of its properties.<\/p>\n<h4 id=\"6eb7\" class=\"graf graf--h4 graf-after--p\"><strong class=\"markup--strong markup--h4-strong\">How to add the listener on the window\u00a0object<\/strong><\/h4>\n<p id=\"cab6\" class=\"graf graf--p graf-after--h4\">The<strong class=\"markup--strong markup--p-strong\">\u00a0addEventListener<\/strong>\u00a0method is the most preferred way to add an event listener to\u00a0<strong class=\"markup--strong markup--p-strong\">window<\/strong>,\u00a0<strong class=\"markup--strong markup--p-strong\">document<\/strong>\u00a0or any other\u00a0<strong class=\"markup--strong markup--p-strong\">element<\/strong>\u00a0in the DOM.<\/p>\n<p id=\"4c32\" class=\"graf graf--p graf-after--p\">There is one more way called \u201con\u201d property onclick, onmouseover, and so on. But is not as useful, as it does not allow us to add multiple event listeners on the same element. The other methods allow it.<\/p>\n<p id=\"e81f\" class=\"graf graf--p graf-after--p\">An\u00a0<strong class=\"markup--strong markup--p-strong\">event<\/strong>\u00a0object is passed as an argument (optional) to the handler which contains all the information related to the event (in our case, mousedown) on the window.<\/p>\n<p id=\"0045\" class=\"graf graf--p graf-after--p\">Open the developer tools (Inspect Element) on this page and copy paste the following code in the console panel and hit enter.<\/p>\n<pre id=\"038e\" class=\"graf graf--pre graf-after--p\">window.addEventListener(\"mousedown\",function(event){\r\n alert(\"window\");\r\n console.log(event);\r\n});<\/pre>\n<p id=\"5865\" class=\"graf graf--p graf-after--pre\">After that, you can go over to any section of the current tab and\u00a0<strong class=\"markup--strong markup--p-strong\">right click\u00a0<\/strong>to see the console and the info related to this event, as shown below in the snapshot.<\/p>\n<p id=\"ba3e\" class=\"graf graf--p graf-after--p\"><strong class=\"markup--strong markup--p-strong\">Note<\/strong>: If you go to any other tab and right click, then this event will not get fired as it belongs to this tab (Window object) only.<\/p>\n<\/div>\n<div class=\"section-inner sectionLayout--fullWidth\">\n<figure id=\"9f78\" class=\"graf graf--figure graf--layoutFillWidth graf-after--p\" data-scroll=\"native\">\n<div class=\"aspectRatioPlaceholder is-locked\">\n<div class=\"aspectRatioPlaceholder-fill\"><\/div>\n<div class=\"progressiveMedia js-progressiveMedia graf-image is-canvasLoaded is-imageLoaded\" data-image-id=\"1*4AuKYuqMQSKBMkI2L081VQ.png\" data-width=\"1366\" data-height=\"728\" data-scroll=\"native\"><canvas class=\"progressiveMedia-canvas js-progressiveMedia-canvas\" width=\"75\" height=\"37\"><\/canvas><img decoding=\"async\" class=\"progressiveMedia-image js-progressiveMedia-image\" src=\"https:\/\/cdn-images-1.medium.com\/max\/2000\/1*4AuKYuqMQSKBMkI2L081VQ.png\" data-src=\"https:\/\/cdn-images-1.medium.com\/max\/2000\/1*4AuKYuqMQSKBMkI2L081VQ.png\" \/><\/div>\n<\/div>\n<\/figure>\n<\/div>\n<div class=\"section-inner sectionLayout--insetColumn\">\n<h4 id=\"4f5b\" class=\"graf graf--h4 graf-after--figure\">The details of the mousedown event<\/h4>\n<p id=\"fe3f\" class=\"graf graf--p graf-after--h4\">In the next few lines, I will explain some of the important captured property corresponding to the\u00a0<strong class=\"markup--strong markup--p-strong\">mousedown<\/strong>\u00a0event we just performed.<\/p>\n<p id=\"8adc\" class=\"graf graf--p graf-after--p\"><strong class=\"markup--strong markup--p-strong\">button<\/strong>: As this was the mousedown event, it will tell you the button you clicked. For the mouse, Left, middle, and right correspond to 0, 1, and 2 respectively. If you click the right button, you can see the value 2.<\/p>\n<p id=\"b680\" class=\"graf graf--p graf-after--p\"><strong class=\"markup--strong markup--p-strong\">clientX<\/strong>\u00a0and\u00a0<strong class=\"markup--strong markup--p-strong\">clientY<\/strong>: Position relative to the upper left of the content area (Viewport). Just analyze the value of these properties with the place you clicked, and you can see how they\u2019re related. Even if you scroll down the page, these properties remain the same. ScreenX and ScreenY reference from the top left of the screen (Monitor).<\/p>\n<p id=\"166c\" class=\"graf graf--p graf-after--p\"><strong class=\"markup--strong markup--p-strong\">altkey \/ ctrlkey<\/strong>: If you keep any of these keys pressed while performing your right click operation, then you can see these values are true. Otherwise, they\u2019re false as in our case.<\/p>\n<p id=\"d726\" class=\"graf graf--p graf-after--p\"><strong class=\"markup--strong markup--p-strong\">target:\u00a0<\/strong>It corresponds to the element you performed the action upon. Whatever element you might have clicked on, you can see the information corresponding to this property in the console<\/p>\n<h4 id=\"d4a9\" class=\"graf graf--h4 graf-after--p\"><strong class=\"markup--strong markup--h4-strong\">What is a document\u00a0object<\/strong>?<\/h4>\n<p id=\"6938\" class=\"graf graf--p graf-after--h4\">The document consists of what is inside the inner window. The\u00a0<strong class=\"markup--strong markup--p-strong\">document<\/strong><strong class=\"markup--strong markup--p-strong\">object<\/strong>\u00a0is the root of every node in the DOM. If you are loading an HTML page in the browser, then the document represents that entire page.<\/p>\n<h3 id=\"6326\" class=\"graf graf--h3 graf-after--p\"><strong class=\"markup--strong markup--h3-strong\">The Event.preventDefault()<\/strong>\u00a0method and its\u00a0usage<\/h3>\n<p id=\"5dde\" class=\"graf graf--p graf-after--h3\">Sometime we don\u2019t want an HTML element to behave in the way it is supposed to behave in default. In such a case, we can use this method.<\/p>\n<p id=\"102a\" class=\"graf graf--p graf-after--p\"><strong class=\"markup--strong markup--p-strong\">Example<\/strong>: Clicking the anchor element will make the browser redirect to that page by default. Let\u2019s try to avoid that.<\/p>\n<pre id=\"9621\" class=\"graf graf--pre graf-after--p\">&lt;html&gt;\r\n&lt;body&gt;<\/pre>\n<pre id=\"ed10\" class=\"graf graf--pre graf-after--pre\">&lt;a href=\"<a class=\"markup--anchor markup--pre-anchor\" href=\"https:\/\/developer.mozilla.org\/\" target=\"_blank\" rel=\"nofollow noopener\" data-href=\"https:\/\/developer.mozilla.org\/\">https:\/\/google.com\/<\/a>\"&gt;Google&lt;\/a&gt;<\/pre>\n<pre id=\"68ba\" class=\"graf graf--pre graf-after--pre\">&lt;script&gt;<\/pre>\n<pre id=\"5963\" class=\"graf graf--pre graf-after--pre\">let link = document.querySelector(\"a\"); \/\/ It is the method to access the first matched element<\/pre>\n<pre id=\"c2f1\" class=\"graf graf--pre graf-after--pre\">link.addEventListener(\"click\", function(event){<\/pre>\n<pre id=\"8f4b\" class=\"graf graf--pre graf-after--pre\">console.log(\"Redirecting Stopped\");<\/pre>\n<pre id=\"2d43\" class=\"graf graf--pre graf-after--pre\">event.preventDefault();<\/pre>\n<pre id=\"f9ec\" class=\"graf graf--pre graf-after--pre\">});<\/pre>\n<pre id=\"0dde\" class=\"graf graf--pre graf-after--pre\">&lt;\/script&gt;\r\n&lt;\/body&gt;\r\n&lt;\/html&gt;<\/pre>\n<p id=\"ed3d\" class=\"graf graf--p graf-after--pre\">You can create an HTML file and check out this code.<\/p>\n<h3 id=\"52c2\" class=\"graf graf--h3 graf-after--p\"><strong class=\"markup--strong markup--h3-strong\">The Event.stopPropagation()\u00a0<\/strong>method<\/h3>\n<p id=\"5eb9\" class=\"graf graf--p graf-after--h3\"><strong class=\"markup--strong markup--p-strong\">Events flow outwards.<\/strong>\u00a0There are certain cases, such as when you have nested elements and you perform some event on a child and it ends up performing some action on the parent, too, that you want to avoid. In such cases, this method is a useful one.<\/p>\n<p id=\"76d6\" class=\"graf graf--p graf-after--p\">It sounds bit confusing, but I hope the below example will make it clear to you.<\/p>\n<p id=\"1473\" class=\"graf graf--p graf-after--p\">Imagine you have a button inside a paragraph and you have attached a mousedown event to both of them. You want to achieve the following use cases:<\/p>\n<ol class=\"postList\">\n<li id=\"26f7\" class=\"graf graf--li graf-after--p\">If you right click the button, then it should show that it has been clicked and does not propagate to the parent element (that is, the paragraph).<\/li>\n<li id=\"fa02\" class=\"graf graf--li graf-after--li\">If you left click on the button, then it should propagate outwards normally and fire the paragraph event listener, too.<\/li>\n<\/ol>\n<p id=\"b989\" class=\"graf graf--p graf-after--li\">Solution:<\/p>\n<pre id=\"4166\" class=\"graf graf--pre graf-after--p\">&lt;html&gt;<\/pre>\n<pre id=\"bb5e\" class=\"graf graf--pre graf-after--pre\">&lt;body&gt;\r\n&lt;p id=\"demo\"&gt; Hello Ho&lt;button id=\"button12\"&gt; Button2 &lt;\/button&gt; &lt;\/p&gt;<\/pre>\n<pre id=\"2217\" class=\"graf graf--pre graf-after--pre\">&lt;script&gt;<\/pre>\n<pre id=\"2231\" class=\"graf graf--pre graf-after--pre\">\/\/ Event Listener on the Button and it's logic<\/pre>\n<pre id=\"eef9\" class=\"graf graf--pre graf-after--pre\">document.getElementById(\"button12\").addEventListener(\"mousedown\",function(event){<\/pre>\n<pre id=\"dcb8\" class=\"graf graf--pre graf-after--pre\">alert(\"button clicked\");<\/pre>\n<pre id=\"9ad0\" class=\"graf graf--pre graf-after--pre\">if(event.button == 2 ) \/\/ Right Click<\/pre>\n<pre id=\"533b\" class=\"graf graf--pre graf-after--pre\">event.stopPropagation();<\/pre>\n<pre id=\"c26f\" class=\"graf graf--pre graf-after--pre\">});<\/pre>\n<pre id=\"3f11\" class=\"graf graf--pre graf-after--pre\">\/\/ Event Listener on the paragraph element with it's logic:<\/pre>\n<pre id=\"4ea7\" class=\"graf graf--pre graf-after--pre\">document.getElementById(\"demo\").addEventListener(\"mousedown\",function(event){<\/pre>\n<pre id=\"d8b2\" class=\"graf graf--pre graf-after--pre\">alert(\"Paragraph clicked\");<\/pre>\n<pre id=\"a496\" class=\"graf graf--pre graf-after--pre\">});<\/pre>\n<pre id=\"a0f8\" class=\"graf graf--pre graf-after--pre\">&lt;\/script&gt;\r\n&lt;\/body&gt;\r\n&lt;\/html&gt;<\/pre>\n<h3 id=\"55d2\" class=\"graf graf--h3 graf-after--pre\"><strong class=\"markup--strong markup--h3-strong\">Removing<\/strong>\u00a0an\u00a0<strong class=\"markup--strong markup--h3-strong\">event listener<\/strong>\u00a0from an\u00a0element<\/h3>\n<p id=\"44b7\" class=\"graf graf--p graf-after--h3\">In order to remove an event listener from an element, we need to call the\u00a0<strong class=\"markup--strong markup--p-strong\">removeEventListener<\/strong>\u00a0method with the event name and the function name.<\/p>\n<p id=\"b552\" class=\"graf graf--p graf-after--p\"><strong class=\"markup--strong markup--p-strong\">Note<\/strong>: when anonymous functions are passed, they don\u2019t have memory mapping. So we need to define those functions outside the callback and then reference them here in the removeEventListener callback.<\/p>\n<pre id=\"6733\" class=\"graf graf--pre graf-after--p\">Document.getElementbyId(\"id_name\").removeEventListener(\"click\",fn_name)<\/pre>\n<p id=\"de30\" class=\"graf graf--p graf-after--pre\">If you have reached this point, you should have a decent understanding of how Event Listeners work in the JavaScript.<\/p>\n<p id=\"3106\" class=\"graf graf--p graf-after--p graf--trailing\">If, while working with your favorite library\/Frameworks, you ever get stuck in the Events Handling part, then these basics should help you to resolve the issue.<\/p>\n<p>&nbsp;<\/p>\n<\/div>\n<h4 class=\"u-lineHeightTightest\"><a class=\"ds-link ds-link--styleSubtle ui-captionStrong u-inlineBlock link link--darken link--darker\" dir=\"auto\" href=\"https:\/\/medium.freecodecamp.org\/@HoneyThakuria?source=post_header_lockup\" data-action=\"show-user-card\" data-action-source=\"post_header_lockup\" data-action-value=\"409038eabc30\" data-action-type=\"hover\" data-user-id=\"409038eabc30\" data-collection-slug=\"free-code-camp\">Honey Thakuria<\/a><\/h4>\n<div class=\"ui-caption ui-xs-clamp2 postMetaInline\">Full Stack Developer, code to solve the problems, which can improve the life of masses<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Photo by\u00a0Sergey Zolkin\u00a0on\u00a0Unsplash In this blog, I will try to make clear the fundamentals of the event handling mechanism in [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":46,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[44,47,29],"tags":[46,31],"class_list":["post-382","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-javascript","category-medium","category-programacion","tag-javascript","tag-programacion"],"_links":{"self":[{"href":"https:\/\/blog.hassler.ec\/wp\/wp-json\/wp\/v2\/posts\/382","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.hassler.ec\/wp\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.hassler.ec\/wp\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.hassler.ec\/wp\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.hassler.ec\/wp\/wp-json\/wp\/v2\/comments?post=382"}],"version-history":[{"count":1,"href":"https:\/\/blog.hassler.ec\/wp\/wp-json\/wp\/v2\/posts\/382\/revisions"}],"predecessor-version":[{"id":383,"href":"https:\/\/blog.hassler.ec\/wp\/wp-json\/wp\/v2\/posts\/382\/revisions\/383"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blog.hassler.ec\/wp\/wp-json\/wp\/v2\/media\/46"}],"wp:attachment":[{"href":"https:\/\/blog.hassler.ec\/wp\/wp-json\/wp\/v2\/media?parent=382"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.hassler.ec\/wp\/wp-json\/wp\/v2\/categories?post=382"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.hassler.ec\/wp\/wp-json\/wp\/v2\/tags?post=382"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}