Blog-Archiv

Mittwoch, 29. Oktober 2014

A JS Starter Kit for Beginners

In case you are interested in JavaScript and HTML, but you do not know how to begin, here is a starter kit for absolute beginners.

JS is a programming language that is interpreted by browsers (no compiler needed). A web browser and a text editor is everything you need. You don't even need internet access.

First create an HTML (Hyper-Text-Markup-Language) document, because JS normally runs in the context of a web page.

HTML Starter

Here is a minimalistic HTML web page you can use as template, copy & paste this into your favorite text editor:

<!DOCTYPE html>
<html>
  <head>
    <title>This will be displayed in the browser title bar.</title>
  </head>
     
  <body>

    <div>
     Here is my web page!
    </div>

  </body>

</html>

If you are on a platform that does not use UTF-8 as encoding, you would either need a text editor that lets you save in UTF-8, or, the better variant, you declare the encoding of your platform in the HTML document (here it is a WINDOWS-compatible encoding for western countries):

  <head>
    <meta charset="ISO-8859-1">

Now save the HTML text into the file system, let's assume you save it to (WINDOWS)

  • C:\me\mypage.html

UNIX people might save it to /home/me/mypage.html.

Now go to your browser and enter following text in the address line on top, and then press ENTER:

file:///C:/me/mypage.html

UNIX people will use file:///home/me/mypage.html.

What your browser now does is

  1. choose a communication protocol named "file:", which connects it to your local hard-disk, and then
  2. read the file in the given path as if it was a web page, and that directory was a web server's directory.

That's it, you should see the content of the web page in your browser now: Here is my web page!

The web pages you normally see in your browser come from the internet and are not stored on your hard-disk (or just temporarily), and you load them using the "http:" protocol and not "file:".
To work with the "http:" protocol you would need to install and start a web server on your machine (Apache, Tomcat, ...), and then make your page available for that web server. For playing around with JS you do not need a running web server, the "file:" protocol will do it.

JS Starter

The initial purpose of JS was to manipulate a web page in a user's browser. So JS mostly runs in the context of an HTML page, although it also can be used as normal scripting language, without HTML, outside of a web browser. But this kind of usage is not recommendable, because JS is full of gotchas and traps, there are much better scripting languages around.

But! As it is the most interpreted language in this world (only few internet pages have no JS in them), we are going to put some of it now into the starter HTML page.

Extend your web page to be the following:

<!DOCTYPE html>
<html>
  <head>
    <title>This will be displayed in the browser title bar.</title>
  </head>
     
  <body>

    <div>
      Here is my web page!
      
      <input value="Click Me" type="button" onclick="trace('Button has been clicked ...');"></input>
      <input value="Clear Me" type="button" onclick="clearTrace();"></input>
    </div>

    <script type="text/javascript">
    </script>

  </body>

</html>

In this HTML page there are two push buttons, the first creates a log line, the second clears all log lines. You see this implemented in the onclick attributes of the input elements, which actually contain JS code. (What you don't yet see here is the implementation of the called functions trace and clearTrace).

Then there is a script element at the end of the page. Script elements are best at the end of the page, because then the document is fully loaded and ready, and maybe the JS code in the script expects that all the HTML document object model (DOM) nodes are already available for manipulation.

Here comes the JS source code of the functions called in the onclick callbacks. Copy & paste it somewhere between the opening and closing script tags.

      var trace = function(text)  {
        var logLine = document.createElement("pre");
        logLine.setAttribute("style", "border: thin solid black;");
        logLine.appendChild(document.createTextNode(text));
        
        var logParagraph = document.getElementById("log");
        if ( ! logParagraph )  {
          logParagraph = document.createElement("p");
          logParagraph.setAttribute("id", "log");
          document.body.appendChild(logParagraph);
        }
        logParagraph.appendChild(logLine);
        
        if (console && console.log)
          console.log(text);
      };
      
      var clearTrace = function()  {
        var logParagraph = document.getElementById("log");
        if (logParagraph)  {
          var len = logParagraph.childNodes.length;
          for (var i = len - 1; i >= 0; i--)
            logParagraph.removeChild(logParagraph.childNodes[i]);
        }
      };
      
      trace("Hello JS log world!");

Now save the content of the web page to disk and press the "Reload" button in your browser (F5, or Ctl-F5). You should see something like this (try it, it works!):

Here is my web page!

On every "Click Me" button click there will be a new log line appended to the page, created by JS. Clicking the "Clear Me" button will clear all generated log lines.

This JS example code represents an output mechanism, logging directly into the page, and trying to write to the browser's console, if it exists and has a log function. (Try F12 to open the browser console, you should see a log line any time you click the "Click Me" button.)

In the first line of trace(), a HTML element of type pre is generated for the log line. The log line is then inserted into that parent element as a text node. Then an element with id="log" is searched in the entire document. When not found, it is created and appended to the end of the document. Then the pre element with the log text is appended to that "log" parent element.
In the clearTrace() function, an element with id "log" is searched, and when found, all child elements are removed from it, thus all log lines will disappear.

This is pure JavaScript, without help of jQuery. But it should run on any browser. You can find documentation about possible JS objects (like window, document, ...) and their properties and functions, including information by which browsers they are supported, on my JS / HtmlUnit report page. There you can click any object, function or property, and you will be taken to the Mozilla documentation page of it.

JS in Files

Of course you want to store your JS code into an external file.
Assuming you would save the JS code into a file named "trace.js" that is in a directory "js" relative to the HTML page, following HTML would represent that:

    <script type="text/javascript" src="js/trace.js"></script>

Replace the previous script tag by this, and your JS file should be read by the browser.
Mind that the script tag MUST NOT be written like that:

<script .... />

It MUST be written like that, else it might not be loaded:

<script .... ></script>

Don't know why, but this is a very popular gotcha.
Here is a HTML line to load the latest version of jQuery. You can put this into the head element:

    <script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>

Better learn jQuery than JavaScript :-)

You can find more help at W3 Schools.
jQuery has a nice tutorial.
For experimenting with JS, js-fiddle is nice.
And here is my private reference.




Keine Kommentare: