Write a comment on this article

Introduction to JavaScript

JavaScript is a scripting language used in most common browsers. It allows you to use functions and operations to interact with the user, which is not possible with HTML only. Unlike PHP, which runs on the server, JavaScript is executed by the local browser. The JavaScript code is delivered together with the HTML and other files like CSS, so the visitor is able to read the code.

JavaScript, despite the name, has absolutely nothing to do with Sun's Java. Its syntax is just very similar to Java, just as well as C or PHP.

You can use the same structures as many other programming languages too like if, while or for. Variables are declared with the keyword "var" and get a suitable datatype when a value is assigned. The datatype may change when assigning different values. The following example demonstrates how variables are handled (you can view an example here: JavaScript_variables.html):

var a;                   // variable a is declared
                         // and is now of type "undefined"
a = 10;                  // a is now of type "number"
a = "10";                // a is now of type "string"
a = new Array(1,2,3);    // a is now of type "object"
                         // (arrays are objects in JavaScript)
a = dummyFunction;       // a is now of type "function"
a = document;            // a is now of type "object"
a = false;               // a is now of type "boolean"
a = null;                // a is now of type "object"
 

JavaScript's power lies in the interaction with the Document Object Model (DOM). The DOM represents an HTML document and provides an API to manipulate its content. Hence, JavaScript is able to alter a document - add elements, change elements (which means you can change the content, value, style, position, etc.) and delete elements. Here are some frequently used methods:

JavasScript provides many predefined functions and objects to work with, e.g. alert. You can also define your own functions and also classes including attributes and methods. Here is an example for a short function to alert (pop up a message box) the date plus a custom message:

// function to alert date with custom message
function alertDate(custom_message){
  var now = new Date();
  var text = now.toUTCString();

  if(custom_message && custom_message!=""){
    text += " ("+custom_message+")";
  }

  alert(text);
}

// call function
alertDate("Hi there!")
 

Where is the code?
There are two ways to use JavaScript with HTML:

  1. External file
    This is the most common way to integrate JavaScript to your page. You can use the element "script" with the attributes "src" and "type" in the head of your document (between <head> and </head>) to include an external file which contains your JavaScript code. The browser will recognize this element and load the file from the webserver.

    If you use XHTML notice that you will have to close the element with a seperate closing tag. Otherwise your document will not validate.

    <script src="../../js/comments.js" type="text/javascript"></script>
     
  2. <Script>
    Another option is to use the "script" element with the attribute "type". You can write your JavaScript code right inside the opening and closing tag. In this case you should use HTML comments to prevent older or JavaScript-disabled browsers from printing the code. You can use this element anywhere in the head or body of your page.

    <script type="text/javascript">
      <!--
        function myFirstFunction(param1,param2){
          // do something
        }
    
        function mySecondFunction(param1,param2){
          // do something else
        }
      // -->
    </script>
     

How do I call it?
You can write JavaScript code in an external file or inside script-tags which will be executed immediately. But mostly, you want to call your functions when a specific event occurs, like the user presses a button or the document finishes loading. For this purpose, many elements HTML have attributes to handle events. Here is a list of what you can use:

The value of these attributes contains JavaScript. You can either call one or more functions or execute any other code.

For example, you can use onmouseover and onmouseout to change an image of a menu. Use onsubmit to check if a form has been filled in correctly or onload to do something when the document finished loading. Imagination has no limits!

The following short example demonstrates how to change a text when the user moves the mouse over it. You can try this script here: JavaScript_events.html.

<p onmouseover="this.innerHTML='You got it!';"
   onmouseout="this.innerHTML='Try me again.';">
  Move your mouse cursor over me.
</p>
 

Not allowed?
Many older browsers and some browsers on mobile devices do not support JavaScript. Also, newer browsers allow to disable the execution of JavaScript. If your webpage relies on JavaScript, you will run into a big problem. This for, you can use the noscript-element. The content of this element is only displayed when the execution of JavaScript is not possible. So you can provide an alternative menu and write a note to the user like in the following example:

<noscript>
  <p>This page requires JavaScript. It seems that your browser
  doesn't support JavaScript or it has been disabled.
  Because the menu is based on JavaScript, here is an alternative:</p>
  
  <ul>
    <li><a href="Home.html">Home</a></li>
    <li><a href="Contact.html">Contact</a></li>
    <li><a href="Archive.html">Archive</a></li>
  </ul>
</noscript>
 

Game of Life
The Game of Life is a famous and simple evolution game designed by John Horton Conway in 1970. It can be implemented in nearly any programming language, here is a possible (and enhanced) solution with JavaScript:

Game of Life with JavaScript

Now you are ready to make your first JavaScript function.

Tags

JavaScript, introduction, scripting

Comments (0)

Leave a comment

If you have a question or a problem and you're looking for a solution, please use the forum. Comments might not be answered.

Your name (required, maximum 255 characters) ( remember)
Your message (required, maximum 5000 characters)
 
Insert these letters into the textfield below: dYTA (required, case-sensitive)
Drag the slider to the right (required)