The correct design of the calling of javascript functions

How to execute function call (js) when clicking on the link, button or any other element. A long time ago I was taught to write the call in the onclick(), but I've seen a few other variants of this action.

So I want to know how did the most right to do it?
October 14th 19 at 12:19
5 answers
October 14th 19 at 12:21
Solution
Right — when it runs, if you are interested in the technique of Unobtrusive Javascript, I advise you to brush up the DOM, starting from the second level, there is a description of the event. It has its fineness and a non-standard implementation in Microsoft Internet Explorer. But I repeat: the true test and right when it all works, and how you did it no one is interested!
October 14th 19 at 12:23

document.getElementById('elementId').onclick = function(event) {
 event = event || window.event;
...
}
On the subject
About Javascript in General. - sonia_Schinner25 commented on October 14th 19 at 12:26
Not good, but if 2 processor? - muriel.Jacobs commented on October 14th 19 at 12:29
Then element.attachEvent( "on"+the name of the event handler) to S, and element.addEventListener( eventName, handler, phase) for the other browsers, which again is available via the link javascript.ru/tutorial/events/intro#reshenie-microsoft,
or use third-party libraries like JQuery. - sonia_Schinner25 commented on October 14th 19 at 12:32
it would at once, no? - Deborah_Predovic commented on October 14th 19 at 12:35
Then:

//universal function
function addEvent(element, event, handler) {
if(-[1,]){
 return element.addEventListener(event, handler, false);
 } else {
 return element.attachEvent('on'+event, handler);
}
}

//testing
addEvent(document.getElementById('test'), 'click', function(event) {
 event = event || window.event;
alert(event);
})

addEvent(document.getElementById('test'), 'click', function(event) {
 event = event || window.event;
alert(2);
})
- sonia_Schinner25 commented on October 14th 19 at 12:38
October 14th 19 at 12:25
1. Hang up event to the selector
2. onclick
3. For links like this: href="javascript:funcName()"
javascript.ru/unsorted/why_href_js_is_bad - sonia_Schinner25 commented on October 14th 19 at 12:28
October 14th 19 at 12:27
to more accurately describe the elements selectors and hang handlers
October 14th 19 at 12:29
You can look at the JQuery library as there is implemented a function call to events like click, change, etc.

Find more questions by tags JavaScript