lewro’s blog - 2.1 - web designer beginner

Avoid inline scripting

August 12, 2007 [11:23 pm]

You may have noticed from my work that I am a big fun of semantic markup. So let’s go straight to the point. When you write semantic html you should always avoid inline scripting and use external scripts instead. The same logic should be definitely used for your CSS as well. If you are on the web standards boat this is no news for you. For all of us who are hooked on web standards this might look like: Hey guys is there any other way? but actually most of the web creators do not think this way. We all wish they would but unfortunately it is not the case yet. There are many reasons why it is like that but let’s not to talk about that right now. For all of you who do not know how I would like to show how to implement progressive enhancement into your web projects.

External java-script

The java-script file should be linked from the head of your html as seen on the image bellow. In some cases web designers link the java-script file from the bottom of the page but that is not an issue here.

image of html code with js linked from the head part of it

Onload function

Ussualy we want java-script fire after the page is fully loaded and for this reason we can use simple onload event inside of our java-script file. Because of the reason we might want to execute more functions when the page is loaded I use the onload function I have found in the Jeremy Keiths book. So let’s see how the function looks like.

image of the java-script code displays onload function

So that is all about it. The page is loaded in the java-script is executed.

The next question is: How can I target elements without inline java-script hooks?

Very simple. You will use document.getElementById or document.getElementsByTagName function. So let’s say you want to change the background color of the paragraph with the ID called intro into red when you click on it.

image of the java-script code displays function which change the background color of the selected paragraph

Deeper knowledge

This is just a very simple example but I am sure you got the point. This way you can attack any DOM element and your HTML can stay clear.You can even create html elements on the fly. I use this technique in my blog for the text resizing function.

More examples together with deeper information about DOM-scripting can be found in books:

RSS 2.0

You can leave a response, or trackback from your own site.

Place for your opinion

* required