Monday, October 24, 2005

hit me with your javascript! hit me!

Ok, let's do some programming. We'll make a button that says "hit me!" but when you do, it shouts "ouch!". Something like this -


Unfortunatly, we can't do that on the blog - it blocks scripts. but no worries. just create an html file and open it in a plain text editor. (and don't ask me how to do that on a mac!)

An html file is a text file that starts with the tag <html> and ends with the corrosponding closing tag </html> Within that, there's usualy a "head" and a "body". So a minimal page would look like:


<html>
<head>
</head>
<body>
</body>
</html>



Try it. Create an empty text file, call it something.html, edit it in a text editor and insert the above. Now save it and open it in your browser.

It's probably not very interesting to look at. Why don't you add some text in the body? Or a title in the head, as in -

<title>groovy hedghogs </title>

Next, the button. So the guys who inveneted HTML thought: "why would there be a button, if not to do provide some input in a form?" Hence a button is a kind of input gizmo, and always part of a form. Which means, its in the context of a form tag. i.e. -


<form>
<input type="button" />
</form>


You also probably want to add a value="something" to your button.

And now - the ouch! For that, we need a bit of JavaScript. Once you get this done, you can call your frinds and tell them you coded. JavaScript is a programming language - or, as the name implies, a scripting language. All it has in common with java is 4 letters. JavaScript allows you to program interactions on web-pages (as oposed to interactions on the server, which are invoked throught the page). Here's a piece of JavaScript:

<script lang=JavaScript">
function boo() {
alert('hoo');
}
</script>

I think its pretty self explanatory. So I'll move on. What you want to do is create a script like this in your page and attach it to the event of a user clicking on your button. So, copy the code (including the script tag) to your page above the button (think why). And add the onclick event handler to your button:
<input type="button" value="blahh" onclick="boo();" />
Done.

Now check if it works, and if you still have the energy, go figure how to pass the text to display as a parameter to the function.

0 Comments:

Post a Comment

<< Home