There are currently three different methods for determining event handlers (a function that runs when a specific event is detected): the traditional method, the W3C method, and the Microsoft method.
Traditional method
In the traditional method, event handlers are determined by setting the onevent property of the element in Javascript (as you do in your sample code) or setting the onevent attribute in the HTML tag (for example, <select onchange="..."> ), although this is the easiest way to use , its use, as a rule, is frowned now because, as you have discovered, it is rather tough - it is not easy to add and remove event handlers to an element to which an event handler is already connected. Also, it is no longer considered good practice to mix javascript with HTML, but it must be contained within or loaded via the <script> .
W3C / Microsoft Methods
The World Wide Web Consortium (W3C) and Microsoft are defining their own event models. Both models work differently, but use different syntaxes. The Microsoft model is used in Internet Explorer, and the W3C model is used in other browsers (Firefox, Opera, Safari, Chrome, etc.). Both of these models have functions for adding event handlers (addEventListener for W3C, attachEvent for Microsoft) and removing event handlers (removeEventListener / detachEvent). This allows you to dynamically add and remove specific handlers for an element; in your case, you can add the first handler based on the first condition, and the second - on the second condition. The βproblemβ with these methods is that there are two of them, and therefore both methods should be used to ensure that your event handler is registered in all browsers (there are also a few subtle differences between the two models, but these differences are not important for the scope application of this issue). In fact, if you look, you will find a large number of "addEvent" functions that use both methods if necessary (and usually return to the traditional method for older browsers). For example, the contest was launched on the QuirksMode blog back in 2005 to create the best "addEvent" function, the result of which (along with the winning function) you can see.
Also, if you use a javascript library like Prototype or jQuery, they have built-in event handling functions that will take care of you above.
Daniel Vandersluis
source share