previous page

Overview | Create HTML | Create CSSl | New HTML | Create Popup | Create Function | User input | Variables | Update Page | Backup | Add Dropdown | Add Loop

next page
Lab 6/7: Introduction to JavaScript

Create popup with JavaScript


Now you'll add the first bit of JavaScript that will generate some action - it will cause a box to pop up when you click on the button

Where does JavaScript go in the HTML page? Mostly it goes in the <head> section, but occasionally it will go in the body. In this case, we'll have a tiny bit of JavaScript right inside an HTML tag - as the value of an attribute.

 

1. Go to the input tag that creates your button, and insert an "onclick" attribute. The resulting line will look like this:

<input type="button" value="print ticket" onclick="alert('You clicked on the button');" />

The "onclick" attribute tells the browser what to do when the button is clicked. (i.e. when there is a "click event"). There are a few other events, they all have names that start with "on..." like "onkeydown", " onmousedown" "onmouseover").

The value of the onclick attribute - this text: alert('You clicked on the button'); - is JavaScript.

IMPORTANT: The first thing to notice is that every JavaScript statement ends in a semi-colon. This is VERY easy to forget and can be VERY frustrating when it makes your program fail to work properly and you can't figure out why. Think of it as a period at the end of a sentence. Without a period, you can't tell where a sentence ends. Without a semicolon, the browser can't tell where the JavaScript statement ends.

The next thing to notice is that there are two parts to this statement:

There is a word followed by parentheses: alert('You clicked on the button')

And there is the contents of the parentheses: alert('You clicked on the button')

You will see this form a lot in programming; a word followed by parentheses with something inside the parenthesis. The "word", in this case "alert" is a JavaScript word that stands for an instruction, or a series of instructions. In this case, the instruction is "open a pop-up box on the computer screen, and put whatever is inside the parentheses into that box".

alert() is unique (most don't do things like open boxes on your screen), but you'll discover that it is very useful.

2. Save your page and view it in a browser (it can be on your desktop, you don't need to put it on your website to view it).

Click on the button...Did a pop-up box appear? If not, go back and check that you typed the line exactly like this:

<input type="button" value="print ticket" onclick="alert('You clicked on the button');" />

3. Go to the Catalyst quiz and answer question #5

Next, you'll start to write a javascript function...

previous page   next page