From 85efc60136a1ccfe8014d63112d590b87434b8c6 Mon Sep 17 00:00:00 2001 From: Adam Shaffer Date: Mon, 11 Mar 2019 09:48:21 -0500 Subject: [PATCH] create addEventListener (#26486) * create addEventListener * Change title to lower case * Rename file to index.md Update and rename addeventlistener file to index.md. Also change front matter block to meet style guide --- .../javascript/add-event-listener/index.md | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 guide/english/javascript/add-event-listener/index.md diff --git a/guide/english/javascript/add-event-listener/index.md b/guide/english/javascript/add-event-listener/index.md new file mode 100644 index 0000000000..e4300f1b45 --- /dev/null +++ b/guide/english/javascript/add-event-listener/index.md @@ -0,0 +1,59 @@ +--- +title: addEventListener +--- +##addEventListener +The addEventListener method assigns a function to a target event for a particular DOM element. In simpler terms this method +says a function or block of code will be executed only when an event is triggered in the HTML DOM. This makes addEventListener +an important tool for making any webpage interactive. + +###Syntax +``` +targetelement.addEventListener(event,callback function); + +where targetelement is the DOM element, event is the event to attach to the DOM element and callback function is the code +initiated when the event is triggered. +``` +###Example +``` +###HTML +
+
+ + + + +
+
+ +###JavaScript +document.getElementbyId(“myButton”).addEventListener(“click”,function(){ + alert(“This button has been clicked”); + }); +``` + +The previous line finds the HTML element with an id of “myButton” and attaches an event listener. In this case, the event is +“click” meaning whenever the use clicks on “myButton” “alert(’This button has been clicked’) “ will be executed. + +###Note### +addEventListener has several advantages . Firstly, it is possible to attach more than one event to a single element. This adds +another layer of interactivity to your website. Second, it clearly separates the javascript code event handling from the HTML +structure. It is best practice that HTML, CSS and Javascript are kept modular. Lastly, it is possible to attach an event handler +to more than one element at once by using className or TagName. For example, the above code could be rewritten +to apply to all the buttons. + +``` +document.getElementsByTagName (“button”).addEventListener(“click”,function(){ + alert(“This button has been clicked”); + }); + + +``` + + +#### Other Resources +Mozilla Developer article on addEventListener + + + +--- +