Proper design of the javascript function call

Asked bytammy krestel

How to make a function call (js) correctly when clicking on a link, button, or any other element. Once upon a time I was taught how to write a call in onclick (), but I saw several other options for this action.

Therefore, I want to know how to do it the most truly?

Answers

sevil
That's right - this is when it works, if you are interested in Unobtrusive Javascript equipment, then I advise you to learn DOM, starting from the second level, there are events described. There are subtleties and stones, for example, non-standard implementation in Microsoft Internet Explorer. But I repeat once again: right and true - this is when everything works, and how you did it is not interesting to anyone!
alex baker

document.getElementById('elementId').onclick = function(event) {
    event = event || window.event;
   ...
}
Replies:
link
 link - kath197king
Not good, but if 2 handlers? - ross aitken smith
Then element.attachEvent (“on” + event name, handler) in IE, and element.addEventListener (event_name, handler, phase) for other browsers, which is again available via link javascript.ru/tutorial/events/intro#reshenie-microsoft,
or use third-party libraries, such as jQuery. - eric muehlstein
so would immediately, no? - janebcolby
Then:
 

//универсальная функция
function addEvent(element, event, handler) {
	if(-[1,]){
		return element.addEventListener(event, handler, false);
	} else {
		return element.attachEvent('on'+event, handler);
	}
}

//тестирование
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);
})
- rapsodi
cyndi
1. Hang the event on the selector
2. onclick
3. For links, you can also do this: href = "javascript: funcName ()"
Replies:
javascript.ru/unsorted/why_href_js_is_bad - dacia
lilmisschainreader
most correctly describe the elements with selectors and hang handlers
falling for books tia
You can look in the JQuery library for how the function calls to click, change, etc. are implemented.
How to make VKontakte Open API work in the 6th and 7th IE :: Computer implementation of painted (student) poker? :: OpenID library for PHP :: What buisness value in F # and where is it applicable in an enterprise? :: Literature on setting up a web server?
Leave Repply forProper design of the javascript function call
Useful Links