Nate's Programming Blog

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.


Name (required)

Email (required)

Website

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Feel free to leave a comment

top