Tuesday, April 01, 2008

JavaScript duh moment

Ok, so, don't laugh. A few days ago I learned something about JavaScript. Something ridiculously basic. Something I should have known for a very long time, but didn't.

Like many Web Developers, I am entirely self-taught. I have never taken a class on Web Development, never formally studied JavaScript or DOM or any of it. Back in the day when I first learned JavaScript, I initially learned how to connect JavaScript to objects, triggered by events. For instance:

<input type="button" onClick="alert('button clicked.');">
Naturally, I assumed that all JavaScript had to be tied to an object. This can be a real pain when you want a JavaScript event to fire independent of any user events, for instance when the page loads. Sometimes you can just use the body tag's onLoad event, but this is not always practical or even possible.

Enter inline JavaScript. Turns out that the other day, I needed to fire a JavaScript event when an Ajax-powered div finished loading. Rather than try to set up events tied to some object in the loaded div page, I simply did the following:

document.write('text here');

And it worked. I had no idea that you can just write JavaScript to a page, and when the page loads in the browser, the JavaScript commands will iterate in the order they are encountered. Good to know. Very useful.

So, like I said, don't laugh. I have been doing this a long time, but never knew that you could just output JavaScript to a page, and it would just run, independent of user events. At the risk of seeming ignorant, I am posting this information out there so that if there are any other old-dogs out there who learned by doing, and don't know this basic behavior yet, now you know.

No comments: