Basic Javascript - part 1

 

This webpage is a bit of a look at JavaScript. I don`t really need it on my website, but maybe I could add some extra odds and sods. Or maybe not.

One of the things that needs to taken into consideration when using JavaScript in webpages is that many people turn off JavaScript functionality in their browsers - JavaScript is often treated with a good deal of suspicion, as it is used for malicious purposes by some websites. However it does have its uses, but I`m not sure that you should really build a website that depends on JavaScript, because the website won`t work if JavaScript is turned off. However it is widely done, all the same.

There is also an accessibility consideration, as most screen readers do not have JavaScript enabled.

One of the things that attracted me to JavaScript is that it has some of its roots in C - some of the syntax is the same, so that should make things a bit easier, as I`ve had a bit of a look at some bits of C a wee while ago.

 

A first JavaScript script

Time to try some basic JavaScript - here`s a minimilist bit of scripting -


     <script type="text/javascript">

     document.write(" *** Here`s a basic line of text produced by JavaScript *** ");

     </script> 

And we get -
 

 
JavaScript has Object Orientated capabilities, "document" is an object, and "write" is a method attached to the object, which loads an output from the script into the webpage.

 

Hiding JavaScript scripts

Now we need to be aware of the fact that many people have JavaScript dis-abled on their browsers, so we can amend that basic script to hide it from browsers without JavaScript enabled. The idea is to hide the JavaScript using HTML comment tags.


     <script type="text/javascript">

     <!--

     document.write(" *** Here`s a basic line of text produced by JavaScript *** ");

     // -->

     </script> 

The browser without JavaScript just sees the script as an HTML comment, so ignores it. A browser with JavaScript enabled sees it as a JavaScript script - JavaScript itself just ignores the HTML comment tags. So we get -
 

 
At least that`s the theory - if I turn off JavaScript on my Firefox browser, I don`t get any of the JavaScript stuff, whether or not I use HTML comment tags or not - maybe there is a difference between having a browser that doesn`t know about JavaScript, and having a browser that does know about JavaScript, but JavaScript is turned off.

As a final comment on this section, the HTML way of adding comments is of course     <!--               -->     rather than     <!--               // -->     However in order that JavaScript doesn`t try to interpret the string     -->    , we comment it using JavaScript syntax, as described in the next section. HTML doesn`t mind, it just treats the two forward slashes as part of the text to be ignored, so just sees it as     -->

Subsequent roaming around on the internet found one or two pages that suggested using the HTML comment tags isn`t neccessary nowadays - it was done in the earlier days of JavaScript when there were a lot of browsers around that didn`t know about JavaScript, so it was a good workaround for that. However all modern browsers know about JavaScript, so the HTML comment tags shouldn`t be used now.

It is back to a problem I keep on getting when looking for information on the internet - very few web pages tell you when they were written, so you have no idea how old they are. Which can be quite confusing, as technologies change so fast.

However, these comment tags have another use - see below for more on this - so maybe they live on.

 

Comments

Another little mod we can do to the basic script above is to add comments within the JavaScript script - there are two ways -

So using two forward slashes, our script could become -


     <script type="text/javascript">

     document.write(" *** Here`s a basic line of text produced by JavaScript *** ");  // this should write this text on the final webpage

     </script> 

Just the line of text is produced, without the comment.
 

 
The forward slash + * notation is the same as used in C, and can be used to comment out a single line, or several lines -


     <script type="text/javascript">

     /* this script will print out
        the line of text without showing
        these comments                    */

     document.write(" *** Here`s a basic line of text produced by JavaScript *** ");

     </script> 

Here is the result, without the comments -
 

 

Including HTML tags

One of the important benefits of JavaScript is to use it to generate HTML code. Here`s a script pretty much the same as the above ones, except I have included the HTML tag for h2 - ie, the second biggest header font. The "document.write" method is used to output the generated code into the browser, and the browser treats it as part of the HTML code within the webpage.


     <script type="text/javascript">

     document.write(" <h2> *** Here`s a line of text with the h2 tag ***  </h2> ");

     </script>

The browser produces the output -
 

 

which rather illustrates how ugly the default heading typefaces are.

Fortunately, you can also include "classes" within the HTML tags, to refer to an external stylesheet. So here is a line of text using the h2 and span tags with classes that refer to the external stylesheet.


     <script type="text/javascript">

     document.write(" <h2  class='h2'> <span class='h2'> *** h2 and span tags with classes  *** </span> </h2> ");

     </script>

Note that I had to change the way that the classes name is quoted - normally you use the double quotes to enclose the name, but JavaScript doesn`t like the double quotes inside the text inside the JavaScript script, I had to change them to single quotes.

 

 

In fact the problem is caused by using double quotes for two different purposes within the same statement. Changing the other double quotes for single quotes works as well.

So the script


     <script type="text/javascript">

     document.write(' <h2  class="h2"> <span class="h2"> *** h2 and span tags with classes  *** </span> </h2> ');

     </script>

produces the same result.

 

 

There is another way to do it, by escaping the inner double quotes - using the \ character. So the script becomes


     <script type="text/javascript">

     document.write(" <h2  class=\"h2\"> <span class=\"h2\"> *** h2 and span tags with classes  *** </span> </h2> ");

     </script>

and produces the same result.

 

 

In the above examples, I have used the document.write method to insert the section of HTML code. It isn`t the only way, document.writeln is another way, and it has an advantage over document.write in that document.writeln automatically adds a new line after the code that has been inserted - document.write doesn`t do that.


     <script type="text/javascript">

     document.writeln(' <h2  class="h2"> <span class="h2"> *** h2 and span tags with classes  *** </span> </h2> ');

     </script>

This produces -

 

 

In addition, there seems to be a community of JavaScript writers who frown on the use of document.write, and want to use document.createElement instead. However it is a bit more complicated, and somewhat beyond basic JavaScript. So for now, I am staying with document.write.

 

HTML tags and validation

There is a problem with producing HTML code in this way - if you like to have your HTML code validated for correct syntax, the validator sees the chevrons inside the JavaScript, and throws up a validation error. It is necessary to hide the chevrons from the validator.

I know of three ways to do this - there may be others.

⇒   use HTML comment tags
the first is to hide the contents of the JavaScript script from the validator by using HTML comment tags. So the script for putting in the <h2> tag becomes

     <script type="text/javascript">

     <!--

     document.write(" <h2> *** Here`s a line of text with the h2 tag ***  </h2> ");

     // -->

     </script>

As described above, the JavaScript interpreter ignores the HTML comment tags, and the validator thinks the inside of the script is a comment, so ignores the code.
It is these comment tags that I have used in this web page.
⇒   use escape characters
the second way is to hide the chevrons from the validator by using escape characters - however JavaScript escape characters are not the same as HTML escape characters -   %3C = <   and   %3E = >   - so the script has to be written as

     <script type="text/javascript">

     document.write(unescape(" %3Ch2%3E *** Here`s a line of text with the h2 tag ***  %3C/h2%3E "));

     </script>

I believe that there is some compatibilty with these two escape characters between JavaScript and PHP.
escape() and unescape() are global functions, but they have been deprecated in ECMAScriptv3.
⇒   use external scripts
the third way is to take your JavaScripts off the web page altogether, and pull them in as required from an external source. There is quite a body of opinion that says that JavaScripts shouldn`t be on the web page at all, it is bad for good clean code, it is bad for validation, and it is bad for accessibility.

 

 

Where do JavaScript scripts go ?

There are three places they can go :-

⇒   in the <head> section
scripts in the <head> section may be coded to run as the browser loads the webpage, or may be coded so they are in effect in storage - they will be run some time later, by an event perhaps, or when called later on
⇒   in the <body> section
scripts in the <body> section are executed as the page is loaded, and so contribute to the way the page looks, or what it does, or even do something completely different - with or without the end-users knowledge
⇒   in an external file
scripts in an external file can be run by including a source reference within the script tags

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

the external file must have the .js file extension
the external file doesn`t have to be in the same folder as the web page, it can be elsewhere on the server, on a different server, or even in a completely different domain - for example -

     <script src="http://www.some-domain.com/thingee.js" type="text/javascript">

the advantage of an external script is that it can be used by any number of different web pages
another way to use an external script is to create a function in the external script, then use another internal JavaScript script to call the function - for this to work the external script has to be referenced in the <head> section of the HTML file

 

Statements

A statement in a JavaScript script is a line of instruction. The JavaScript has to do something. So in all the various scripts above, the line -


     document.write(" *** Here`s a basic line of text produced by JavaScript *** ");

is a statement. Usually a statement is ended with a semi-colon. It is not essential, but normally each statement goes on a separate line. Strictly speaking, a single statement on its own line doesn`t need a semi-colon, however it is good practice to always add the semi-colon.

A statement may contain one or more of the JavaScript action keywords, such as "if", or "else", or "case", or "return". Or it can be used to declare a variable, or to run a previously specified function. JavaScript also allows a completely empty statement.

 

Variables

Variables in JavaScript are like variables in lots of other languages - they are the names for virtual containers that contain some kind of value.

They are created, or declared, by a var statement - this statement creates, or declares, a variable called "result" -


     var result;

The variable can be filled with a value at the time of declaration -


     var result=100;

After it has been declared, the contents of a variable can be changed with another statement -


     result=99;

A variable doesn`t have to contain a number, it can contain a text string -


     var conclusion="the script has worked well";

Variable names in JavaScript must start with either an alphabetic character, or the underscore character, and they are case sensitive, so "Result" and "result" would be different variables.

The only non-alphanumeric character allowed in variable names is the underscore character - it can be used to combine words into longer, more descriptive, names - for example "tea_pot". Another technique that is considered good practice is to use an uppercase letter to show the start of the second word, instead of the underscore - for example "teaPot".

You can of course use variables that contain numbers in arithmetic processes.


     result=sum+1;

However in a significant difference from C, variables in JavaScript don`t have to contain data of a specified type - a JavaScript variable can quite happily contain either numbers, or text. In fact the type of the content can be changed part way through a script - that could fairly add a confusion factor to a script.

Variables in JavaScript can be of two types -

If you want to confuse yourself, you can have a global variable and a local variable with the same name - but at some point they are guaranteed to get mixed up, so why make life difficult.

 

Arithmetic Operators

JavaScript contains a number of arithmetic operators -

 

Assignment Operators

JavaScript also contains a number of assignment operators - the basic one is the equals sign, the others are really shorthand ways of doing things - personally I think they just add confusion.

One of the nice things is that if you have two variables containing text strings, you can concatenate the two text strings into a third variable, or presumably print them out using a document.write statement - using the + operator.

 

Comparison Operators

JavaScript also contains a number of comparison operators - these do a comparison between any of -

and return an answer of "true" or "false". These operators are used in conditional statements.

 

Logical Operators

JavaScript also contains logical operators, so that conditional statements can contain more than one comparison operation within the one statement -

 

Conditional Operators

JavaScript also contains a conditional operator, but the operator is not just one or two characters like all the above, it is specified by the way the statement is written -


     variableX=(condition) ? "a":"b";

If the condition is true, then variableX is given the value "a" - if the condition is not true, then variableX is given the value "b".

Once again, to me personally, it seems to be a confusing shortcut - the meaning of the statement would be much clearer using the classic "if -- else" conditional statements.

 

if...else statements

Like many programming languages, JavaScript contains its own syntax for "if...else" logic. Like C, it only uses the two keywords "if" and "else".

JavaScript doesn`t use the three additional keywords that are used in Unix / Linux Bash shell scripts - "then", "elif", and "fi".

Also like C, it uses curly brackets to enclose the action to be taken - though so far I haven`t found out if the curly brackets are mandatory or optional - some texts put them in, some don`t.

If you want to nest "if" statements, then "else if" is used.

You can of course just use the "if" keyword if the logic doesn`t require a second choice.

So the basic format is -


     if ( condition-1 )
     
       { 
          action-a;            // executed if condition-1 is true

          action-b;            // also executed if condition-1 is true
       }

     else 

       {
          action-c;           // executed if condition-1 is false

          action-d;           // also executed if condition-1 is false
       }

Or -


     if ( condition-1 )
     
       { 
          action-a;            // executed if condition-1 is true
       }

     else if ( condition-2 )

       {
          action-b;           // executed if condition-2 is true
       }

     else 

       {
          action-c;           // executed if both condition-1 and condition-2 are false
       }

 

switch ...case statements

Switch...case statements are another way of selecting one of a block of code to run out of several blocks, depending on the value of an expression - the expression could be something like the contents of a variable, for example.

Switch ...case statements in JavaScript seem to be pretty much the same as switch...case statements in C.

The basic construct looks like :-


     var some_value=x;

     switch (some_value)
 
        {

           case 1:                   // if some_value = 1, then perform action-a
               action-a;
               break;

           case 2:                   // if some_value = 2, then perform action-b
               action-b;
               break;

           case 3:                   // if some_value = 3, then perform action-c
               action-c;
               break;

           default:                  // if some_value does not equal 1, 2, or 3, then perform action-d
               action-d;

          }

The default case is optional, if you don`t have it, the switch...case does nothing, if none of the cases produce a match.

The break; statement in each case stops the script going any further, once a match has been found. If you don`t have it in each case, the script performs every one of the actions one after the other, even without a match.

The switch..case statement is a neater way of having multiple choices, rather than using a succession of "else if" statements.

 

 

 

This page is getting a bit long now, so more in page 2, to follow.

 

 

 

 

 

website design by ron-t

 

website hosting by freevirtualservers.com

 

© 2024   Ron Turner

 

+                                   +  

 

Link to the W3C website.   Link to the W3C website.