JavaScript: Using Event Listeners, attaching handlers on page load, and DOMContentLoaded
March 21, 2008 on 9:03 pm | In AJAX, JavaScript | No CommentsFor anybody who has ever coded any JavaScript at all, they are no doubt familiar with events such as “onclick”, “onmouseover”, “onmousemove”, and more. In old HTML web pages, it was very common to add these attributes to <a> tags to achieve some special effects.
Later on, browsers begin to support these attributes even in other tags like <div>, and pretty much anything else.
However, as web standards develop over the years and people’s coding practices for the web begin to standardize, it is generally considered bad practice to use them. There are many reasons for this, among others:
- You cannot attach more than 1 action this way. If you want to do a lot of things in one event, you will need to put a lot of code either in this attribute, or in the function being called from this attribute; and these may very well be unrelated actions. This makes your code less organized and harder to develop.
- No good separation of presentation (HTML) from functionality (JavaScript). Everything is mixed together. This makes collaboration development efforts difficult; and makes the code hard for you to manage even if you were the sole developer.
Fortunately, we have an alternative solution. They are Event Listeners.
Powered by WordPress with Pool theme design by Borja Fernandez.
Entries and comments feeds.
Valid XHTML and CSS. ^Top^
Save in del.icio.us
StumbleUpon this