Best practice of adding event listeners (javascript, html)

I know that I can ask for the moon here, but I am looking for some experienced opinions on how best to add event listeners or, rather, "When" or "Where" to add them to the js file.

Take my example. I have a page that has a bunch of onclick events that should now be handled by properties in the JS file

eg,

var test = document.getElementById("i-am-element"); test.onclick = testEventListener; 

My question is where exactly should I add this to the js file.

As I planned to go about this, I needed something like the following

 $(document).ready(function() { var test = document.getElementById("test-me-shane"); test.onclick = testEventListener; //add all the functions to different elements }); myfunction1(){} myfunction2(){} myfunction3(){} 

So, as soon as the document is ready, only then all event listeners will be added. Is this acceptable or is there a more common way to do this.

NOTE. I know this question may seem subjective, so I will go with the correct answer, which will be the most popular way you saw when event listeners added. I am sure that most of this should be accepted, and I apologize in advance if it is similar to where you should declare variables, at the beginning or as needed.

In Java, should variables be declared at the top of the function or as needed?

+6
source share
2 answers

You really want all event listeners to be in one place; What for? Just for easy maintenance.

Because of this, it is best to place all event listeners in a place where you can guarantee that all the elements that you want to associate with event handlers are available.

This is why the most common place to bind event handlers occurs after the DOMReady event DOMReady $(document).ready() .

As always, there are some exceptions to the rule. Very sometimes, you may need to bind an event handler to an element as soon as available; which after closing the element tag has been defined. In this case, use the following snippet:

 <div id="arbitrary-parent"> <h1 id="arbitrary-element">I need an event handler bound to me <strong>immediately!</strong></h1> <script>document.getElementById("arbitrary-element").onclick = function () { alert("clicked"); }</script> </div> 

Another thing you should consider is how you are going to bind your handlers. If you stick with: DOMElement.onclick = function () { }; , you limit yourself to being bound to an event handler.

Instead, the following approach allows you to bind muliple handlers for each event:

 function bind(el, evt, func) { if (el.addEventListener){ el.addEventListener(evt, func, false); } else if (el.attachEvent) { el.attachEvent('on' + evt, func); } } 
+7
source

Is there a specific reason why you are not just specifying an association when declaring an element in html
<someTag id="i-am-an-element" onclick="functionToTheEventToExecute()"> </someTag>
, I think so.

+1
source

Source: https://habr.com/ru/post/894181/


All Articles