Conditionals

o       Up until now, our JavaScript projects have been unable to alter their behaviour spontaneously. When a page loads with our JavaScript embedded within, it is unable to do anything other than what we expect, time and again.

o       The only difference we have seen is in the use of a prompt box to alter what is shown on a page. However, the page essentially does the same thing with the text provided, regardless of what text is typed in.

o       What would be really handy would be to give JavaScript a mechanism to make decisions. For example, if we provided a prompt box asking the visitor for their name, it might be nice to have a list of “known names” that could be greeted differently from any other visitors to the site.

o      Conditional statements give us that ability, and are key to working with JavaScript.

o     A conditional statement consists of three parts:

o     A test (often with a comparison operator, or comparator) to see if a given condition is true or false.

o     A block of code that is performed if and only if the condition is true.

o     An optional block of code that is performed if and only if the condition is false.

These three parts are represented in JavaScript as follows:

  if ( conditional_test )

  {

  JavaScript statement;

  JavaScript statement;

  JavaScript statement;

  …   } else

  {

  JavaScript statement;

  JavaScript statement;

  JavaScript statement;

  …

  }

o     Everything from the first closing curly bracket (or brace) is optional, so the following is also a valid conditional prototype: 

 if ( conditional_test )

  {

  JavaScript statement;

  JavaScript statement;

  JavaScript statement;

  …   }

o     In this case, if the conditional_test does not return true, nothing happens.

o   An example of  complete conditional statement is as follows:

 if ( var_1 > var_2 )

  {

  alert(“Variable 1 is greater”);

  } else   {

  alert(“Variable 2 is greater”);

 }

  Note that the above condition is not necessarily always correct. Consider the case where var_1 is equal to var_2.

In that case, the above code will produce the message that “Variable 2 is greater”, since var_1 > var_2 returns false. In this case, we want to add an additional condition to the else branch of code: 

if ( var_1 > var_2 )

  {

  alert(“Variable 1 is greater”);

  } else

if ( var_1 < var_2 )

  {

  alert(“Variable 2 is greater”);

 }

o In this case, equality will produce no output, as neither of the conditions will return true. For completeness, we could add a final else branch to the statement:

 if ( var_1 > var_2 )

  {

  alert(“Variable 1 is greater”);

  }  else

if ( var_1 < var_2 )

  {

  alert(“Variable 2 is greater”);

 }

else   {

  alert(“The variables are equal”);

 }

o      Note that in this case, we don’t have to check for equality in the final branch, as if var_1 is neither greater than nor less than   var_2, then – numerically at least – the two must be equal.

o     We can continue adding as many else if statements as required to this stack.

If you only have one statement following your conditional test, the braces may be omitted:

 if ( var_1 > var_2 )

  alert(“Variable 2 is greater”);

However, if you later want to add further statements to this conditional branch, you will have to add braces around the block, and this can lead to confusion. It is recommended that you use braces to enclose all blocks of conditional code. o Consider the following block of code:

 if ( var_1 > 4 )   {

  var_2 = var_1;

 }

else   {   var_2 = 4;   }

o     This code is rather long, but achieves comparatively little – var_2 is equal to var_1 or 4, whichever is greater. o A more compact way of writing this could be:

Read More

Alert, Prompt and Confirm

o    So far, we have seen brief examples of alertprompt and confirm dialogue boxes to request a response from the user, and to pause all code in the background until the request is satisfied.

o    All of these boxes are the result of methods of the window object. This object is the highest level object that JavaScript can deal with in a browser. As such, all other objects on a page (with a few exceptions) are actually properties of the window object.

o     Because of this ubiquity, its presence is assumed even if it is omitted. Thus, where we technically should write:

 window.document.write(“…”);

 it is equally valid to write:

 document.write(“…”);

 as we have been doing.

o     Similarly, instead of writing:

 window.alert(“…”);

we can happily write:

 alert(“…”);

o    The prototypes of the three methods are:

        window.alert( message ); window.confirm( message ); window.prompt( message, default_response );

o    Alert will always return a value of “true” when it is cleared by clicking “ok”.

o    Confirm will return either “true” or “false” depending on the response chosen to clear the box.

o    Prompt will return either the value typed in, “null” if nothing is typed in, and “false” if the box is cancelled.

Project

o   Open your previous project file, and save it under the name chapter_10.html.

o   Clear the previous redirection code, and ensure that the script tags have been returned to the head section of the document.

o   Add a new statement to the script on the page that will display the following message before the rest of the page is shown:

 Welcome to my website! Click OK to continue.

o Check your page in your browser.

 o   We will use alertconfirm, and prompt throughout this course. Take a moment to try each of them in turn on this page, each time stopping to review your changes.

 o   Use the write method of the document object to check the return values of each method. For example:

          document.write(alert(“hello world”));

Read More

About Comments

o   Repeat after me : Comments are important. Comments are importantComments are important.

o   Adding comments to your code is always good practice. As the complexity of your scripts grows, comments help you (and others) understand their structure when you come to view the code at a later date.

o   A lot of code created quickly is said to be “write only” code, as it suffers from an inherent lack of structure or commenting. Debugging such code, or reusing it months later, becomes maddeningly impossible as you try to remember what a certain line was supposed to do, or why using certain values seems to stop your code from working.

o   Comments are completely ignored by JavaScript and have no effect on the speed at which your scripts run, provided they are properly formed.

o   Comments can slow the loading of your page, however – many coders keep a “development” copy of their code fully commented for editing, and remove all comments from their code when they finally publish it.

o   There are two types of comment in JavaScript – single line comments, and multi-line comments.

o   Single line comments begin with two forward-slash characters (//), and end with a new line:

// this is a comment

 alert(“hello”); // so is this

o   Single line comments in JavaScript can also use the HTML comment format that you may be familiar with:

 <!– this is a comment

 alert(“hello”);

o   Note two things: firstly, this use of the HTML comment format does not require a closing –> tag. Secondly, this is only a one line comment, unlike its use in HTML, which comments all lines until the closing comment tag.

o   You can add multiple-line comments by enclosing the comment block between /* and */. For example:

/* all of this text is going to be ignored by JavaScript. This allows us to write larger comments without worrying about having to individually “comment out” each line */ 

alert(“Hello World”);

/* a one line, “mult-line” comment */

o   As well as adding narrative to your script, you can use comments to remove code from your pages without having to delete the code. For example:

// this was the old message

// alert(“Hello World”); // and this is the new message alert(“Hello everyone!”);

o   This can be very useful if you are trying to track down an error in your code – you can “comment out” each suspect line in turn until you manage to get your code working again.

Project

o   Open your previous project file, and save it under the name chapter_7.html

o   Add the single line comment

This is my first comment

to the beginning of your script.

Add a multi-line comment to your script, replacing your previous single line comment. The multi-line comment should describe what your script does at present. 

Read More

Hiding Scripts from Older Browsers

    • Very old browsers don’t understand JavaScript. There are very few such browsers in use today, but two factors force us to continue to consider environments that may not be able to cope with our JavaScript code.
    • Firstly, all modern browsers allow users to control whether JavaScript code will be run. In many cases, users will not have any say over their company policy, and may not even know that their work machine has had JavaScript disabled.
    • Secondly, not all of your visitors will be using browsers that can make any use of JavaScript. Braille displays, screen readers and other non-visual browsers have little use for many JavaScript tricks. In addition, search engines like Google will ignore any JavaScript you use on your pages, potentially hiding important content and causing your pages to remain unindexed.
    • Browsers that don’t support JavaScript are supposed to ignore anything between the opening and closing script tags. However, many break this rule and will attempt to render your code as HTML, with potentially embarrassing consequences.
    • However, we can use the fact that <!– denotes a single line comment in JavaScript but a multi-line comment in HTML to ensure that our code is seen by a JavaScript-savvy browser, but ignored as commented-out HTML by anything else:

               <script>

      <!– hide  from older browsers

     … your code

     // stop hiding code –> </script>

o   This prevents older browsers from displaying the code, but what if we want to replace this with some comment. For example, let’s say we had a bit of code that displayed the time of day and greeted our user by name. Without JavaScript and using the method above, there would simply be a blank on the page where the greeting should have been.

o   We can use the <noscript> tag to cause our code to “fail gracefully” where JavaScript has been disabled or is unavailable. The contents of this element will be ignored where JavaScript is understood, and displayed anywhere else.

For example:

<noscript>

    <h1>Welcome to our site!</h1>

</noscript>

<script>

<!– hide  from older browsers

… code to customise header

// stop hiding code –>

</script>

Project 

o   Open your previous project file, and save it under the name chapter_8.html.

o   Add two lines to your code to ensure that it will not confuse older browsers or browsers where the user has disabled JavaScript.

o   Add a noscript element to explain what your JavaScript does.

    It is generally considered “bad form” to instruct your user to “upgrade to a better browser”, as this can insult many people

   who use assistive devices – consider this form of advice to be similar to the advice that tells a blind person “to get some

    glasses”.

o   Instead where possible you should use the noscript element to provide content that adequately replaces the scripted content

    with a suitable replacement. For example, if you use your JavaScript to build a navigation panel on your page, the noscript element should contain a plain HTML list that does the same job.

Read More

Python Strings

27Aug  Admin

Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable. For example −

a = 'Hello World!'

You can display a string  with the print() function:

x = “Welcome”    #Assigning a string to a variable
print(x)

Output– Welcome

Read More

Automatically Redirecting the User

o   We have already briefly seen the use of browser redirection in chapter 4.

o   To formulate the idea more completely, in order to redirect the user to a different page, you set the location property of the document objects.

o   As we saw in chapter 6, we can use the assignment operator here. For example:

 document.location = “http://www.bbc.co.uk/”; document.location = “chapter_4.html”;

Project

o   Open your previous project file, and save it under the name chapter_9_redirect.html.

o   Save another copy of the file, this time called chapter_9.html.

o   Make sure both files are saved in the same folder, and that you have chapter_9.html open in your editor.

o   Remove all script from between the script tags, except for your browser hiding lines. Make sure that the script tags are still in the head section of the page.

o   Now, add a single statement to this script that will automatically redirect the user to the page

chapter_9_redirect.html as soon as the page is loaded into a browser.

o   Finally, add a header tag to the body section of the page containing the text “You can’t see me!”.

o   Close this page, don’t check it in a browser yet, and open the page chapter_9_redirect.html in your editor.

o   Remove all JavaScript from this page (including your script tags) and ensure that only HTML remains on the page.

o   Add a header tag to the body section of the page containing the text “But you can see ME!”.

o   Save this page, and load the page chapter_9.html into your browser.

                Experiment with various positions for the script tags on chapter_9.html to see if you can make the header appear before the    redirection.

Read More

Comparisons

o       Comparison operators compare two values with each other. Most commonly, they are used to compare the contents of two variables – for example we might want to check if the value of var_1 was numerically greater than that of var_2.

o        When you use a comparison operator, the value that is returned from the comparison is invariably a Boolean value of either true or false. For example, consider the following statements:

var_1 = 4; var_2 = 10;

var_3 = var_1 > var_2;

           In this case, the value of var_3 is false. Note that the Boolean value of false is not the same as the text string “false”:

var_4 = false;  // Boolean value var_5 = “false”;  // Text string o Common comparison operators are given below:

Comparison

Function

x == y

Returns true if x and y are equivalent, false otherwise

x != y

Returns true if x and y are not equivalent, false otherwise

x > y

Returns true if x is numerically greater than y, false otherwise

x >= y

Returns true if x is numerically greater than or equal to y, false otherwise

x < y

Returns true if y is numerically greater than x, false otherwise

x <= yReturns true if y is numerically greater than or equal to x, false otherwise

o       To reverse the value returned from a comparison, we generally modify the comparison operator with a ! (a “bang”). Note that in many cases this is not necessary, but can aid comprehension:

var_1 !> var_2; var_1 <= var_2;

                    both of these are equivalent, but one may make more semantic sense in a given context than the other.

Project

o   Open your previous project file, and save it under the name chapter_12.html.

o   Ensure that your two variables both have numerical values in them and not strings.

o   Use an alert box to display the result of a comparison of your two variables for each of the comparison operators listed above.

o   Substitute one of the numerical values for a text string and repeat the procedure. Note the differences.

Read More

Assigning Values to Properties

o   While objects and methods allow us to do things on a page, such as alter the content or pop up dialogue boxes to interact with theuser,     in many cases we will want to alter the value of one of an object’s properties directly. These cases are akin to painting our piano green.

o   Given our discussion on methods so far, we might expect to be able to alter our object’s properties by using a method – for example, the following would seem logical:

 piano.paint(“green”);

o   In many cases, that is exactly what we will do. However, there are two drawbacks here. The first is that, within this course, the majority of objects that we discover are built into and defined by our browser. If we rely on using a method to alter an object’s property, we are also relying on the fact that the method exists in the first place.

o   A much more direct way to solve this problem is to access the object’s properties directly. For example:

piano.colour  =  “green”;

o   Here we are no longer using a method to perform an action, we are using what is known as an operator. In this case, the operator has the symbol “=”, and is known as the assignment operator.

o   Within JavaScript, we can use this operator to great effectiveness. For example, we could alter the title element of a document (the text that is displayed in the top bar of the browser’s window) dynamically. This could be done when a user clicked on a part of the page using an event handler (more later on this), or could be set to automatically update each minute to show the current time in the page title. The code we would use for this task is simple:

document.title  =  “a new title”;

o   There are many assignment operators in JavaScript. Some of the more common are shown in the table below:

 Assignment  Function
x = ySets the value of x to y
x += ySets the value of x to x+y
x -= ySets the value of x to x-y
x *=ySets the value of x to x times y
x /=ySets the value of x to x divided by y

o   Not all assignment operators work with all types of values. But the addition assignment operator works with both numbers and text. When dealing with numbers, the result will be the sum of the two numbers. When dealing with text (technically called strings), the result will be the concatenation of the two strings:

document.title += “!”;

will cause the symbol “!” to be appended to the end of the current document title.

Project

o   Open your previous project file, and save it under the name chapter_6.html

o   Remove any existing JavaScript from your script tags, but leave the tags in place ready for some new JavaScript.

o   Use your text editor to change the value of the title element of the page as follows, then load your page into a browser and view the result:

<title>With a little help from</title>

o   Now, add a statement to our script element to add the following text to the end of the current title:

”JavaScript for Beginners!”;

o   Reload the page in your browser and note the title bar of the window.

o   If the display looks odd, consider your use of spaces…

o   All we have so far is an example that does nothing more than HTML could manage. Let’s introduce a new method of the window object to help us to add a little more dynamism and interaction to the script. Change the value of the title tag as follows:

<title>Chapter 6: Assigning Values to Properties</title>

o   Now, remove your previous JavaScript statement and insert the following:

document.title =     window.prompt(“Your title?”, “”);

o Reload your page and consider the result.

o   We have come across the window object before. Our demonstration of the alert method in chapter 4 could have been more properly written as:

window.alert(“message”);

In many cases, we can omit certain parts of our object/property/method hierarchy when writing our code. We will discuss this again later.

o   To understand what is going on with our prompt method, we can write down a method prototype. This is a way of describing a method’s arguments in such a way that their effect on the method is more self explanatory. A prototype for the prompt method of the window object might look like the following:

window.prompt( message, default_response );

o   So, we can see that the first argument defines the text that appears as the question in the prompt dialogue box. The second argument is a little less clear. Try your code with different values and see what difference your changes make.

o   Finally, we note that this prompt method somehow takes the information typed into the box and passes it to our JavaScript assignment. Say someone typed “Hello World” into the box. It would have been as if our assignment had actually been:

document.title = “Hello World”;

o   When this sort of passing of values occurs, it is said that the method has returned the value passed. In this case, we would say that “the prompt method has returned the value ‘Hello World’”, or that “the return value of the prompt method was ‘Hello World’”.

o   Return values will become very important when we deal with event handlers later on.

Read More

Objects, Properties and Methods

12 Apr  Admin

o   Generally speaking, objects are “things”. For example, a piano is an object.

o   Properties are terms that can describe and define a particular object. Our piano, for example, has a colour, a weight, a height, pedals, a keyboard and a lid.

o      Note from the above that an object’s properties can be properties themselves. So we have the case where a piano lid is a property of the piano, but is also an object in its own right, with its own set of properties – for example, the lid has a colour, a length, and even a state of either open or closed.

o     If objects are the nouns of a programming language and properties are the adjectives, then methods are the verbs. Methods are actions that can be performed on (or by) a particular object. To continue our piano example, you could play a piano, open its lid, or press the sustain pedal.

o      Many programming languages have similar ways of referring to objects and their properties or methods. In general, they are hierarchical, and an object’s relationship with its properties and methods, as well as with other objects, can often be easily seen from the programming notation.

o      In JavaScript, we use a “dot notation” to represent objects and their properties and methods. For example, we would refer to our piano’s colour in the following way:

 piano.colour;

o     If we wanted to instruct JavaScript to play the piano, we could write something as simple as:

 piano.play();

o     A clear example of object hierarchy could be seen if we decided to open the lid of the piano:

 piano.lid.open();

o     Or even more so if we wanted to press the sustain pedal of the piano:

 piano.pedals.sustain.press();

o     Note that in some of the examples above, we have brackets () after each set of words, and in some we don’t. This has to do with making sure that JavaScript can understand what we say.

o     JavaScript works with objects throughout its existence in a web browser. All HTML elements on a page can be described as objects, properties or methods. We have already seen a few of these objects in our previous introductory chapter:

 document.write(…); document.location;

o   In these examples, document is an object, while write is a method and location is a property.

o      In these lines, we see a clue about the use of brackets in these statements. We use brackets to signify to JavaScript that we are talking about an object’s method, and not a property of the same name.

o     Brackets also allow us to pass certain extra information to an object’s method. In the above example, to write the text “Hello world!” to a web page document, we would write the following JavaScript:

 document.write(“Hello World”);

o     Each method can do different things depending on what is put in the brackets (or “passed to the method as an argument”, to use the technical term). Indeed, many methods can take multiple “arguments” to modify its behaviour. Multiple arguments are separated by a comma (,).

o     A JavaScript instruction  like those shown here is referred to as a JavaScript statement. All statements should end in a single semi-colon (;). JavaScript will often ignore missed semi-colons at the end of lines, and insert the semi-colon for you. However, this can cause some unexpected results. Consider the following:

document.write(“<h1>Hello World! </h1>”);

o     In many other languages, this would be acceptable. However, JavaScript will often interpret something like this as the following: 

document.write(“<h1>;Hello World!; </h1>”);

o     This interpretation will generate an error, as JavaScript will complain if you end a statement without ensuring that any terms between quotes have matching pairs of quotes. In this example, the first line’s “statement” is cut short, and JavaScript will fall over.

o    For this reason, it is recommended that all your statements should end with semi-colons.

Read More

A tour of javascript

 26 Aug Admin

         Let’s start with a quick tour of the major features of JavaScript. This chapter is intended to be a showcase of what JavaScript can do, not an in depth investigation into the deeper concepts, so don’t worry too much if you get lost or don’t understand the code you’re typing in!

Project –

  • Our JavaScript is all going to be written using NotePad. Open NotePad and save the resulting empty document  in your user drive as chapter_4.html.
  • Begin by creating a basic HTML page in your blank document. It doesn’t have to be anything fancy – the following will be more than sufficient:

<html> <head>

  <title>Chapter 4: A Tour of JavaScript</title>

</head>

<body>

<h1>A Tour of JavaScript</h1>

</body>

</html>

  • As a convention, when the notes intend that you should enter code all on one line, they will use an arrow as  above to indicate that you should not take a new line at that point. With HTML, this is rarely important, but with JavaScript, a new line in the wrong place can stop your code from working.

Save your new webpage, and view it in your web browser. For the moment, use Internet Explorer to view this page. To do this, find your saved file on your user drive, and double-click on it. This will open the file in Internet Explorer by default, and let you see the header you’ve just created.

  • So far, we haven’t done anything beyond the scope of HTML. Let’s add some JavaScript to the page.
  • There are (generally speaking) three places in a web page where we can add JavaScript. The first of these is between a new set of HTML tags. These script tags take the following form:

<script language=”JavaScript” type=”text/JavaScript”>

… code …

</script>

  o   The script element above can be placed virtually anywhere you could place any element in an HTML page – in           otherwords, in either the head element or the body element. It is most commonly placed in the former, though this is usually so that all your code can be easily found on the page.

o   Note too that there is no arbitrary limit on the number of script elements that can be contained in an HTML page. There is nothing stopping you from having a hundred of these dotted around your pages, except perhaps prudence.

o   Let’s add our opening and closing script tags to the head element of the page, like so: 

<html>

<head>

<title> … </title>    

<script language=”JavaScript” type=”text/JavaScript”>

 </script>

</head> 

Save the file, and then try refreshing your page in the browser window. Note that nothing has happened. This is what we expected – all we have done so far is to set up an area of the page to hold our JavaScript.

   Go back to NotePad and enter the following text between the opening and closing script tags:

window.alert(“Hello world!”);

Save your changes, and again refresh your page in the browser window. Welcome to the world of JavaScript!

Go back to notepad and remove the window.alert line you just added. Now add the following, slightly more complex code: 

if  ( confirm(“Go to Google?”) )  {    

document.location  = “http://www.google.com/”;

}

 o   Again, save your changes and refresh the page. For those with an eye to future chapters, this is an example of a conditional statement, where we ask JavaScript to check the condition of something (in this case, our response to a question) and then to alter its behaviour based on what it finds.

 o   Now, both of these bits of JavaScript have run uncontrollably when the page has loaded into the browser. In most cases, we will want to have more control over when our JavaScript does what we ask it to.

o   This control is the domain of events. In a browser, every element of an HTML document has associated with it a number of events that can happen to it. Links can be clicked, forms can be submitted, pages can be loaded and so on.

o   Modify the previous lines of JavaScript in your script element to match the following: 

function  go_to_google() {  

if  ( confirm(“Go to Google?”) )  {    

document.location  =“http://www.google.com/”;

}

}

Be careful with your brackets here!

o   Save and refresh, and note that nothing happens this time. This is because we have enclosed the previous action (popping up a question and acting on the response) within a function. A function is a block of code that is given a name – in this case, the name is go_to_google() – and is only run when that name is “called”. It can be useful to think of functions as magic spells that can be invoked when their name is said.

o   To invoke this spell, we need to choose an element on the page to trigger it. A natural candidate is a link element, so add the following HTML to the body section of your page: 

<p>A quick <a href=”#”>test</a>.</p>

o   The # link is a common HTML trick that allows us to create a “link to nowhere”. 

o   Save and refresh, and check that the link appears on the page, and that it goes nowhere when clicked.

o   Now, we want to have our page ask us if we want to “Go to Google?” when we click on that link. Here’s how

o   Take the link element, and modify it as follows: 

<a href=”#” onclick=”go_to_google();”>test</a>

o Save and refresh, and then click on the link. This is an example of an event handler. When the link is clicked (onclick), our browser says the “magic words” go_to_google(), and our function is invoked.

          o   For our final trick, add the following code to the body section of the page, after the paragraph containing the link: 

<body>

<script language=”JavaScript” type=”text/JavaScript”>

document.write(“<h2>Here’s another    header!</h2>”);

</script>

o   Note that the line of code should be all on one line! Save the page and refresh the browser. Note that we now have a new line of text on the page – another header! We’ve used JavaScript to create HTML and tell the browser to display it appropriately. In this example, JavaScript has done nothing that we couldn’t have done with a line of HTML, but in future chapters we will see how we can use this to write the current date and more.

Read More