Save jsalert.html as jsevent.html and delete the script element (remember an element is the opening tag, the closing tag and anything between them).
In the paragraph put an HTML span around the word script.
Add an attribute to the opening span tag so it looks like this:
<span onmouseover="alert('Hello again');">
Save and view. Hover your mouse cursor over the word script. You should see the alert message dialog box pop up.
Normally you would give the user a clue that there is something special about the word script. They need to know to move the mouse to it. What you do depends on the situation but this to illustrate the point:
<span style="color:red;" onmouseover="alert('Hello again');">
Save and view and the word should now be red but the JavaScript should do the same.
Three languages
If you can grasp the structure of the above code you have grasped one of the most difficult things about Web development. In that one chunk of text are three different languages! It is vital you do understand so read on. The HTML looks like this:
<span onmouseover="" style="">
HTML uses double quotes (speech marks) to enclose values. You already know that span is HTML. The onmouseover attribute is one of the many HTML attributes and so is style. The stuff inside the double quotes will not be HTML though. The CSS looks like this:
color:red;
and the JavaScript looks like this:
alert('Hello again');
JavaScript can use single or double quotes but if you use single it will be easier to spot which quotes are JavaScript and which are HTML.
Hopefully you now understand that line of code and what it does:
- it tells the browser that there is a span element
- the span element has a style attribute so the browser knows to look inside the double quotes for some styles and apply those in-line styles to the span element
- the onmouseover attribute tells the browser to start watching to see if the user moves their mouse over the span (known as an event)
- if the user does that the browser will run the JavaScript code which is known as an event trigger.
You already learned that things get a bit messy if you put CSS inside the HTML (in-line CSS). JavaScript is much the same. Most of the time you put it in an external file or at the top of the page and not inside tags as you have done here.
Event-driven
You would not normal ask the browser to "run" the scripts straight away as you did in jsalert.html. JavaScript is an event-driven language. This means that the things the user does trigger the code to run just as you did here. You can just have things happen when the page loads but often you want to let the user control when JavaScript runs.
Enough words. Try changing onmouseover to onmouseup. Save and view then click with your mouse on the red word. There are many events but those are two of the most common ones. The up bit refers to when you let go of your mouse button.