A little fun with Javascript

Javascript is a programming language that lets you add a little interactivity to a web page, beyond what we’ve done with adding links.  The simplest piece of javascript you can write puts a little alert window on the screen.  To use javascript, we’ll take over one of our links.

index_html

 

Note that the link goes to “#”, which means “go to the page I’m already on.”  But the onclick attribute calls a javascript function called “alert”.

Give this a try.

Now lets do something more.  Alert is a built in function of javascript.  Instead, lets write our own function.  Say you want a link to go to a random page. Say the player choose to fight a bear, and you’ve decided that the player will lose 70% of the time, and win 30% of the time.   We’ll write our own javascript function, called fight( ).  Put the following in the head of your page, between <head> and </head>.

index_html

 

You’ve added a little program to your page!  Now we can use the little program, which sends us to either lose.html or win.html (we still have to write those pages!)

index_html

 

We use our own fight( ) function just like we used the alert( ) function.

Lastly, we can change things on our page using javascript.  This one is more complicated.  Say we have a link called “Talk to the Bear.”  If the user clicks that, it should make a part of the web page, that was invisible, become visible.  We can do this with a combination of HTML, CSS, and javascript.

First, we need the words that will become visible.  Make a <div> tag with an id.  An id is similar to a class, and labels a single element on a page.

index_html

 

To make this div hidden, we add the following to the stylesheet for this page.  The hashtag (#) on a CSS page means ‘id=’

style_css

 

This makes the element with id=”talk” hidden.

Then we add a new javascript function, between <script> and </script>.  index_html

 

This changes the style of the element from display:none to display:block (which is the normal way things are displayed.)

Finally, we add a link that calls the javascript function.

index_html

 

That was quite a lot!  Its confusing to learn three different languages at once!  HTML, CSS, and javascript all look different from each other.  Make sure you are putting the right code in the right place!