How to make a function call(js) when clicking on a link, button or any other element.A long time ago I was taught how to write a call in onclick(), but I saw several other variants of this action.

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

5 Answers 5

True - this is when it works, if you are interested in Unobtrusive Javascript, then I advise you to learn DOM , starting from the second level, events are described there.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!
most correctly describe the elements with selectors and hang handlers
You can look in the jQuery library as it implements calling functions for events like click, change, etc.
1.Hang the event on the selector
2.onclick
3.For links it is possible and so: href="javascript: funcName()"

document.getElementById('elementId').onclick=function(event) {
    event=event || window.event;
 ...
}
  • Badly, and if 2 handlers? – Inquisitive Impala Sep 7 '10 at 14:50
  • Then element.attachEvent (“on” + event name, handler) in IE, and element.addEventListener (event_name, handler, phase) for other browsers, which is also available via the link javascript.ru/tutorial/events/intro # reshenie-microsoft,
    or use third-party libraries, such as jQuery.
    – Soviet8 Sep 7 '10 at 14:53
  • so and at once, not? – Enthusiastic97 Sep 7 '10 at 15:23
  • 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);
    })
    
    – Soviet8 Sep 7 '10 at 15:37