I know I may be asking for the moon here but I'm looking for some experienced opinons on the best way to add event listeners or rather 'When' or 'Where' to add them in the js file.
Take my take as an example. I have a page which has a bunch of onclick events that now have to be handled by properties in the JS file
eg
var test = document.getElementById("i-am-element");
test.onclick = testEventListener;
My question is where exactly I should add this in the js file.
How I was planning to go about it was to have 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 that once the document is ready, only then are all the event listeners added. Is this acceptable or is there are more universally accepted way of doing it.
NOTE: I know this question may appear subjective so I'm going with the correct answer will be the most popular way you've seen seen event listeners added. I'm sure there must be a majority acceptance on this and I apologize in advance if its similiar to something like where you should declare variables, at the start or when you need them.
In Java, should variables be declared at the top of a function, or as they're needed?
See Question&Answers more detail:os