A brief introduction to JavaScript

Javascript is another scripting language. It is recognized and executed by most browsers. The main distinction between php and javascript is this:
As a result, Javascript can do different things. It cannot access resources on the server, but it can respond immediately and locally to what the user of the browser does. In particular, javascript can respond to events, such as:
    Click, Change, MouseOver, Submit (of a form)

How does it differ from PHP?

The syntax is basically the same. All the funny symbols you learned: =, ==, !, &&, etc. are the same. if, function ...

Where do you put Javascript in an HTML document?

Between <script>  ...  </script> tags. Wherever you want to write something (usually variable). In the <head> section where you are not writing, for instance, for declaring a function.
It is possible that your javascript will be ignored. Clients can disable javascript entirely, if you use it to bother them. So you may need to provide alternatives. This is done between
<noscript>  .. </noscript> tags, where you put HTML that will only be rendered when javascript cannot be executed. Example:
<script>
document.write("Hello from " + myname);
</script>
<noscript>
Hello from me
</noscript>
You can also put javascript inside html tags, The javascript, whatever it is, will be carried out when the event happens. For instance:
<em onMouseOver="this.style.color='red'"
onMouseOut="this.style.color='blue';"> try this </em>
What does this do? Well, try this now. But avoid clicking on this.

3 popup boxes

For getting input from a user, there are 3 Javascript functions that pop up a box. Each takes one argument, a string that will be displayed in the box. They are:

Finding your errors!

If your script is "not working" it may be that there is an error. You might expect an error message, as we got in PHP. But, browsers do not show Javascript errors, because your user will not like to see them. (In the early days error messages were really "In your face.") So, open the Console (shows Javascript and CSS errors)
Open the console and try:

Click on this line to provoke an error

The error might even be detected before you click on the line
the line in question contains:
onclick="alert('this is invalid' Javascript) varx=2+;"

You might want to clear the console initially, and reload the page you are debugging -- There are usually a lot of errors from "professional" pages! The Console tries to show you exactly where an error is detected. Remember, the actual mistake may be several lines before.


What next?

An important use of Javascript is to check a form for required elements and reasonable values. We will discuss this at length in the next chapter.