Unobtrusive JavascriptCategory: Programming, Web Design | Leave a Comment |
17 08 2005 |
It’s one of the coolest new techniques I’ve learned. Hate having ugly javascript events in your html? Want to get rid of them entirely and also take advantage of caching all the javascript to a static file? Well now you can with unobtrusive javascript. Basically the idea is that you can use the onload event and snag the elements that you need javascript events on using something like document.getElementById and then just dynamically apply that event directly to the element. Here is an example.
window.onload = function() {
document.getElementById(‘myPrintLink’).onclick = function() {
window.print();
};
};
Now I have a javascript event attached to my print link to open the print dialogue box when clicked. It is that easy and no js in the html. One of the biggest advantages to this is now your designers can create mock html pages that are in fact the final product and the developer never has to touch it, just as long as it uses good css design and provides sufficient ids to access the elements that need to be accessed.