Using Event Handlers

o      So far, our scripts have run as soon as the browser page has loaded. Even when we have used functions to “package” our code, those functions have run as soon as they have been called in the page, or not at all if no call was made. In other words, the only event our scripts have so far responded to has been the event of our page loading into the browser window.

o       Most of the time, however, you will want your code to respond specifically to user activities. You will want to define functions, and have them spring into action only when the user does something. Enter event handlers.

o       Every time a user interacts with the page, the browser tells JavaScript about an “event” happening. That event could be a mouse click, a mouse pointer moving over or out of a given element (such as an image or a paragraph), a user tabbing to a new part of an HTML form, the user leaving the page, the user submitting a form and so on.

o       An event handler is a bit of JavaScript code that allows us to capture each event as it happens, and respond to it by running some JavaScript code.

o       In general, we attach event handlers to specific HTML tags, so a mouse click on one element of the page might be captured by an event handler, but clicking somewhere else might do something completely different, or indeed nothing at all. o Some common event handlers are in the table below:

Event Handler

Occurs When…

onloadAn element is loaded on the page

onunload

An element is not loaded, for example when a user leaves a page

onmouseoverWhen the mouse pointer enters the area defined by an HTML element

onmouseout

When the mouse pointer leaves the area defined by an HTML element

onclickWhen the left mouse button is clicked within the area defined by an HTML element

onmousedown

When the left mouse button is depressed within the area defined by an HTML element

onmouseupWhen the left mouse button is released within the area defined by an HTML element

o      The last three are related, but there are subtle differences – onclick is defined as being when both mousedown and mouseup events happen in the given element’s area. For example, if you click on an area of the page, that registers the area’s mousedown event. If you then hold the mouse down and move to another area before releasing, it will register the other area’s mouseup event. The browser’s click event, however, will remain unregistered.

o     In theory, we can add most of these event handlers to just about any HTML tag we want. In practise, many browsers restrict what we can interact with.

o      We will mostly be attaching event handlers to <img><a> and <body> tags.

o      To attach an event handler to a tag, we use the following method:

            <a href=”…” onclick=”a_function();”>link</a>

o       We can use this method to attach any event handler listed above to the elements of the page. In addition to calling functions (with any optional arguments, of course), we can write JavaScript directly into our event handlers:

          <a href=”…” onclick=”alert(‘hello’);”>link</a>

o      Note the potential issue with quote marks here – if you use double quotes around your event handler, you need to use single quotes within and vice versa.

Project

o       Open your previous project file, and save it under the name chapter_21.html. o Clear all JavaScript code from your script tags.

o      Ensure that you have a script element in the head area of your document, and none in the body area.

o      Within the head area script element, define the following function:

       function set_status( msg )

     {

      window.status = msg; }

o        When called, this function will set the text displayed in the browser’s status bar (the part of the window below the page content) to whatever is passed as an argument. For example, to set the status bar to display “Welcome”, we would call:

             set_status(“Welcome”);

o   Now define the following function immediately below the last:

        function clear_status( )

      {

        set_status(“”); }

o       When called, this function will clear the status bar. Notice that we are using our previous function within the new one. This is a common programming technique that allows us to define functions of specific cases using more general functions.

o       Now, add the following HTML to the body area of your page. Remember, we’re adding HTML here, not JavaScript, so do not be tempted to use script tags for this part of the project:

            <a href=”#” 

     onmouseover=”set_status(‘hello’);” onmouseout=”clear_status();”>testing</a>

o      Load the page in your browser and observe what happens when you move your mouse over the link.

o     The # value for the href attribute of the link allows us to define a “dead” link on the page. Clicking on the link will take you nowhere – try it.

o     Now, alter the code to have the link point at a real website that you know of.

o     Clicking on the link now will take you away from the page. Let’s say we want to suppress that behaviour.

o      When an event handler intercepts an event, it pauses the normal action of the event. For example, if you used an onclick handler on a link to pop up an alert box, the link would only be followed after the alert box had been dismissed. We can use event handlers to cancel the action if required by using their return values.

o     Add a new function to the head area script element:

        function confirm_link( )

   {   check = confirm(“This will take you away from our site. Are you sure?”);   return check; }

o      The value of check will be true or false.

o      Now, modify your link to contain the following event handler:

onclick=”return confirm_link();”

       By using the word return in our event handler, the response of the function will be used to decide whether the rest of the normal action is run. In this case, if confirm_link() returns false, our link action will be cancelled. o Load your page in your browser and view the result.

Read More

Logical Operators

o       In our discussion of conditionals, we saw how to check the veracity of a single condition via a comparator:

 if ( x > some_value )

{

  …expressions… }

o       We have also seen the limitations of such an approach. Let us say we wanted to discover if lay between two values, say val_1 and val_2. There are a number of ways we could achieve this. In our example on student grades, we learned that we could use an if…else pair to achieve this effect:

    if ( x > val_1 )

  {

    …do something…

  } else

    if ( x > val_2 )

 {

   …do something else… }

o       The above code achieves what we want – for the second branch, x must lie between val_2 and val_1 (assuming val_1 is greater than val_2, of course). However, it’s rather unwieldy, and does not scale elegantly to checking three conditions (say we wanted to check if x was an even number as well), or in fact to ten conditions.

o       Enter Logical Operators. These operators are used to join together conditional checks and return true or false depending on whether all or any of the checks are true.

o      In English, we refer to these operators by using the words “AND” and “OR”.

o       For example, say we wanted to do something each Tuesday at 8pm. We would want to check whether the current day was Tuesday, and whether the time was 8pm.

o       Another example: Let’s say we wanted to do something on the first Tuesday of each month, and also on the 3rd of the month as well. We would have to check whether the current day was the first Tuesday of the month, or whether it was the 3rd day of the month. 

Note in the last example, if both conditions were true, then we would be on Tuesday the 3rd and would perform the action. In other words, an or condition allows for either one, or the other, or bothconditions to be true.

o      In JavaScript, we use the following syntax to check multiple conditions:

       ( 100 > 10 && 5 < 8 )

translates as “if 100 is greater than 10 and 5 is less than 8”. In this case, the result is true.

       ( 100 > 200 && 4 < 9 )

in this case, the result is false. Note here that only the first condition is actually checked. Since and requires both comparisons to be true, as soon as it finds a false one it stops checking. This can be useful.

       ( 100 > 10 || 9 < 8 )

translates as “if 100 is greater than 10 or 9 is less than 8”. In this case, the result is true, since at least one of the conditions is met.

       ( 100 > 200 || 4 > 9 )

in this case, the result is false since neither of the comparisons are true. Finally:

       ( 100 > 200 || 5 < 2 || 3 > 2 )

in this case, the result is true. Any one of the three being true will provide this result.

o     As we can see from the last example, this method of checking scales to any number of conditions. We can also mix and match the operators. For example:

               ( ( 100 > 200 && 100 > 300 ) || 100 > 2 )

in this case, the and condition evaluates to false, but since either that or the last condition has to be true to return true, the overall condition returns true as 100 is indeed greater than 2.

o      This sort of complex logic can take a while to comprehend, and will not form a set part of the course. However, it is useful to be aware of it.

Project

o   Open your previous project file, and save it under the name chapter_20.html. o Clear all JavaScript code from your script tags.

o    Ensure that you have a script element in the head area of your document, and one in the body area.

o      Copy the file available_plugins.js from the network drive (your tutor will demonstrate this), and open it using NotePad’s File > Open command.

o       Copy and paste the entire contents of available_plugins.js into your current project file, into the script element in the head area of your page.

o      Have a read through the code. Note that it defines a large, two dimensional array. The array has a list of various components that can be present in web browsers (such as Flash or Quicktime)

o      Add a function to the head area script element, called flash_exists(). This function should use a for loop to check each of the elements of the available_plugins array and establish if Flash is present.

o     Add a further function to the head area script element, called quicktime_exists(). This function should also use a for loop to check each element of the array, this time returning true if Quicktime is present. o Finally, add a function to the head area script element called both_quicktime_and_flash_exist(). This function should call both of the previous functions, store their results in a variable, and produce an alert box containing the message: o “Both Quicktime and Flash” if both functions returned true; or:

o   “One of Quicktime or Flash is missing” if either of the functions return false.

       Call the final function from the body area script element.

o  Check your results in your browser.

Read More

Using Functions

o    A function is a named set of JavaScript statements that perform a task and appear inside the standard <script> tags. The task can be simple or complex, and the name of the function is up to you, within similar constraints to the naming of variables.

o     JavaScript functions are declared before they are used. The declaration looks like this:

     function name_of_function( )

  {

    …your code here… }

o       Unlike all the JavaScript instructions we have looked at so far, the code inside a function will not be run until specifically requested. Such a request is called a function call.

o       Functions can be called from anywhere on the page that JavaScript can live, but must be called after the function has been declared. For example, if you declare a function in the body of a document and then call it from the head of the document, you may find that the browser returns an error message. For this reason, most JavaScript programmers define any functions they are going to use between <script> tags in the head section of their pages to ensure that they are all defined before they are used.

o        Functions are to object methods as variables are to object properties – they are also called in a similar manner. To run the code contained in the name_of_function function above, we would use the following line of code:

     name_of_function();

Note the parentheses after the function name. This lets JavaScript know that we are dealing with a function and not a variable. The parentheses also allow us to “pass” extra information to the function, which can alter its behaviour.

Consider the following function:

        function greet_user( username )

    {

       message = “Hello “ + username;   alert(message); }

o         Whenever the function is called, it will greet the user named.

How can we pass this information through? Consider:

      greet_user(“Anisa”);

or

   var_1 = prompt(“Name?”, “”); greet_user(var_1);

o   We should use functions in our code as often as possible. Whenever we perform an action that isn’t accomplished by the use of a method or an assignment operator, we should try to build a function that can accomplish the task.

o      For example, we can build a function to check email addresses:

   function check_email( address )

   {   var_1 = false;

   if ( address.match(/^.+@.+..+$/) )

   {     var_1 = true;

   } }

o       The above function will take a string that is passed to it (often called the function’s argument), and will alter the value of var_1 depending on what it finds. However, the function is lacking an important ability – the ability to communicate its findings back out to the rest of the script.

We have mentioned return values a few times in the notes. Now we see a situation that requires a function to return its findings to the rest of the code. Ideally, we’d like to be able to use the above function as follows:

   if ( check_email(address) )

  {

   …do some email things… }

o         In order for this to work, the return value from check_email would have to be a Boolean value. We can arrange this quite simply:

        function check_email( address )

   {   var_1 = false;

   if ( address.match(/^.+@.+..+$/) )

   {     var_1 = true;   }   return var_1; }

o        Since var_1 is either true or false, the returned value will be Boolean. We can even skip the use of the variable here and be more direct: 

  function check_email( address )

  {

   if ( address.match(/^.+@.+..+$/) )

   {     return true;   }   return false;

  }

Or even better, since address.match() will return a Boolean value of its own:

     function check_email( address )

    {

     return address.match(/^.+@.+..+$);

    }

The above function may not seem like a great saving. After all, we are using four lines of code to define a function that performs only one line of code. Compare:

       function check_email( address )

    {

      return address.match(/^.+@.+..+$);

    }

      if ( check_email(address) )

   {

     …do some email things…

   }

   with:

  if ( address.match(/^.+@.+..+$/) )

 {

   …do some email things… }

o       While the benefits here are not obvious, consider the case where, at some point in the future, you discover a better method of checking for email addresses. In the second case above, you will have to search your code for each and every instance of that method, and replace it with your new method, which may not be one line of code. In the first case, you will just have to change the underlying function definition, and the “upgrade” will be effective throughout your code without you having to update each occurrence.

Project 

o      Open your previous project file, and save it under the name chapter_19.html. o Clear all JavaScript code from your script tags.

o     Ensure that you have a script element in the head area of your document, and one in the body area.

o       In the head area, define a function called show_message. This function should take one argument, called message, and should use an alert box to display the contents of the argument.

o      In the body area, call the function with various messages as arguments.

o    Now use a variable in the body area to store the return value of a prompt asking the user for a message. Use this variable as the argument to a single instance of show_message.

o      Define a new function in the head area called get_message. It should take no argument, but should replicate the function of your prompt in the body area and ask the user for a message via a prompt box.

o       Make sure that get_message returns a sensible value. We are aiming to replace our prompt statement in the body area with the following code:

message = get_message();

so consider what you will have to return to enable this to work.

o      Once you are happy with your get_message definition, try replacing your prompt code in the body area with the statement above.

o     To demonstrate the power of functions, change the action of show_message to write the message to the page without changing any code in the body area of the page.

Read More

String Manipulation

o    Throughout your use of JavaScript in a production environment, you will often use it to read values from variables, and alter a behaviour based on what it finds.

o   We have already seen some basic string reading in the section on comparisons where we test for equality. However, this allor-nothing approach is often not subtle enough for our purposes.

o   Take the case where we want to check a user’s name against a list of known users. If the user enters their name as “Karen”, for example, that will be fine if and only if they spell the name precisely as we have it recorded, including capitalisation etc. If the user decides to type in her full name, say “Karen Aaronofsky”, the code will not recognise her.

o   In this case, we want to see if the text “Karen” appears at all in the string. We call this substring searching, and it can be incredibly useful.

o   One of the simplest substring searches is done by using the indexOf method. Every string-type variable has this method associated with it. Consider this code:

      var_1 = “Deepika Sharma”;

      var_2 = var_1.indexOf(“Deepika”);

In this case, the value of var_2 will be 0 – remembering that JavaScript begins counting at 0!

o   If we were to search for a surname here: 

      var_1 = “Deepika Sharma”;

      var_2 = var_1.indexOf(“Sharma”);

      var_2 will have a value of 6.

o   Finally, if the search were to “fail”, so say we searched for the name “Anisa” as a substring, the value of var_2 would then be -1.

o   Note that this is more flexible, but still presents an issue if the user forgets to capitalise any of the substrings that we are searching for – in JavaScript, “Karen” does not equal “karen”.

o   In order to get around this, we might want to ensure that capitalisation is not taken into account. A simple way to achieve this is to force strings into lowercase before the check is performed:

    real_name = “Deepika”; name = prompt(“Your name?”,””);

   real_name = real_name.toLowerCase(); try_name = try_name.toLowerCase();

   if ( try_name.indexOf(real_name) > -1 )

     alert(“Hello Deepika!”);

} else

{

// note we use the original,  // non-lower-cased name here  alert(“Welcome “ + name); }

o   There are a number of string methods we can use to perform “value checks” on strings. A few are printed in the following table:

MethodBehaviour
String.indexOf(“str”)

Returns the numerical position of the first character of the substring “str” in the String

String.charAt(x)

Returns the character at position x in the string – the opposite of indexOf

String.toLowerCase()

Returns a copy of the string with all capital letters replaced by their lowercase counterparts

String.toUpperCase()

Returns a copy of the string with all lowercase letters replaced by their capital counterparts

String.match(/exp/)

Returns true or false based on a regular expression search of the string

o   The final method here deserves some comment. What is a regular expression?

o   A regular expression is a standard way of writing down a “pattern” of characters that is easily recognisable. For example, consider a typical email address:

                   jonathan@relativesanity.com

o   An email address follows a “pattern” which makes it instantly recognisable as an email address to a human. Wouldn’t it be handy if we could define that pattern in JavaScript for a browser to use? Regular expressions allow us to do just that.

o   Let’s look at our email address again. We can break it down to a “prototype” email address as follows:

                           [some letters]@[some more letters].[a few more letters]

o   Of course, it’s slightly more complex than that – there are some characters which aren’t allowed to be in certain parts of the email address (no spaces, for example), but this lets you see the idea of breaking this string up into required “chunks”.

o   Now, to convert this to a regular expression. Just as we use quote marks to denote (or “delimit”) string values in JavaScript, to signify a regular expression, we use forward slashes: /. Our email address regular expression might look like this:

            /^.+@.+..+$/

o   This warrants some discussion. Let’s look at this a character at a time:

o   / denotes the start of the regular expression

o   ^ denotes that we want this regular expression to be found at the very beginning of the string we are searching.

o   .+ the dot symbol is used to stand in for any character. The plus signifies we want to find at least one of those. So this is equivalent to our plain-English phrase [some letters].

o   @ this is simply a character – it has no special meaning other than to say we want to find an @ character after at least one character from the beginning of the string.

o   .+ the same as before – at least one more character after the @.

o   . This is interesting. We know that the dot symbol has a special meaning in a regular expression – it means “match any character”. However, here we want to find an actual dot. Unlike @, which has no special meaning, we have to tell JavaScript to ignore the dots special meaning. We do this by preceding it with a backslash, which tells JavaScript to treat the character immediately following it as though it has no special meaning. This is a convention you will come across many times while programming. The net result here is that we want to match a dot after a series of characters.

o   .+ and again, at least one more character after the dot.

o   $ this is the mirror of the ^ at the beginning – this matches the end of the tested string.

o   / tells JavaScript we are at the end of the regular expression..

o   Phew! Lots to consider here. Regular expressions are an arcane art at the best of times, so don’t worry too much if the above code is indecipherable. The important thing to realise at the moment is that we can perform some quite sophisticated pattern recognition in JavaScript without having to resort to checking each individual character of a string multiple times.

The following code checks a variable to see if it looks like an email address:

     var_1 = prompt(“Your email?”, “”);

     if ( var_1.match(/^.+@.+..+$/) )

{

     alert(“valid email address”);

} else {

     alert(“are you sure?”); }

o   There are a few problems with this code at the moment – for example, it will pass the string “-@-.-“ quite happily, which is clearly wrong. We will look at ways around this later on in the course.

Project 

    o   Open your previous project file, and save it under the name chapter_18.html. o Clear all JavaScript code from your script tags.

    o   Use a prompt box to capture some user input to a variable called check_string.

    o   Use a document.write statement to output the results of each of the various string methods when applied to the user input.

         o   Check the user input to see if it’s an email address, and alter your output accordingly to either “That’s an email address” or “That doesn’t look like an email address to me!”

    o   In the latter case, output the failed string as well so that the user can see their input and modify it next time, if appropriate.

Read More

Python Casting

27Aug  Admin

Casting is when you convert a variable value from one type to another. This is, in Python, done with functions such as int() or float() or str()

Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.

Casting in python is therefore done using constructor functions:

  • int()

This Python cast function is used to construct any integral number with the help of an integral literal, a string literal (obtained by rounding down the previous whole number), or a float literal (a whole number is represented by providing a string).

Example

x = int(2)
y = int(4.8)
z = int(“8”)
print(x)
print(y)
print(z)

Output

2

4

8

  • float()

This construction function helps in the construction of any float number with the help of a float literal, an integral literal, or a string literal (if a float or an integer is represented by a string).

Example

x = float(4)
y = float(7.8)
z = float(“5”)
w = float(“2.4”)
print(x)
print(y)
print(z)
print(w)

Output

4.0
7.8
5.0
2.4

  • str()

This construction function helps in the construction of any string with the help of a lot of different data types.

Example

x = str(“s2”)
y = str(9)
z = str(5.0)
print(x)
print(y)
print(z)


Output

s2
9
5.0

Read More

Javascript Array Types

There are four types of array in javascript:

  • Homogeneous arrays
  • Heterogeneous arrays
  • Multidimensional arrays
  • Jagged arrays

Homogeneous Arrays

As the name may suggest a homogeneous array is an array that stores a single data type(string, int or Boolean values).

var array = ["Yamini", "Aman", "Yuvraj"];
var array = [21, 25, 27];
var array = [true, false, true];

Heterogeneous Arrays

A heterogeneous array is the opposite to a homogeneous array. Meaning it can store mixed data types.

var array = ["Yamini", 21, true];

Multidimensional Arrays

Also known as an array of arrays, multidimensional arrays allow you to store arrays within arrays, a kind of “array-ception”.

var array = [["Yamini", "21"], ["Aman", "25"], ["Yuvraj", "27"]];

Jagged Arrays

Jagged arrays are similar to multidimensional array with the exception being that a jagged array does not require a uniform set of data.

var array = [
    ["Yamini", "21", "Developer"],
    ["Aman", "25"],
    ["Yuvraj"]
];
Read More

Python Numbers

 27 Aug  Admin

Three numeric types in python:

  • int- Integers are whole numbers. They can be positive or negative. They must be without decimal values.
  • float- A floating point number contain decimal points. It can be positive or negative
  • complex- A complex number contains two part – real and imaginary. The imaginary part is written with the “j” suffix.

Example-

a = 4
b = 8.6
c = 2j 
print(type(a))
print(type(b))
print(type(c))
Output-

<class ‘int’>
<class ‘float’>
<class ‘complex’>

Read More

Arrays

o      In many cases, variables will completely satisfy our data storage needs in JavaScript. However, in a large number of cases, we may wish to “group” variables into a collection of related items.

o      Take, for example, days of the week. In each day we perform a number of tasks, so we could want to record each task as a separate item under a group called, say, Monday’s Tasks.

o       In JavaScript, to achieve this we would store each task in a separate variable, and then group those variables together into an array.

o       An array is a special type of JavaScript object that can store multiple data values – unlike a variable, which can only store one data value at a time.

o       It could be helpful to think of an array as a row of mail boxes in an office, just as you might think of a variable as a single, solitary mail box.

o       The boxes in an array are numbered upwards, starting at box number 0 – note that counting begins at 0 here, just as we discussed in the previous chapter. The number assigned to each box is known as its index.

In order to use an array in JavaScript, you must first create it. There are a number of ways to create arrays in JavaScript. The simplest follows:

           arrDays = new Array();

This statement creates a new, empty array called arrDays. We can call arrays just like we can variables, but with a few minor adjustments.

o       If you already know how many elements a given array will have, you can declare this explicitly: 

 arrDays = new Array(7);

This modification creates an array with 7 empty boxes. However, arrays will expand and contract to the required size in JavaScript, so the cases where you will need to state the size of the array are rare.

o        More useful, however, is the ability to “fill” the boxes of an array when you create it. For example: 

 arrDays = new Array(“Monday”,”Tuesday”);

We now have an array with two elements. The first (element 0) has a value of “Monday”, while the second (element 1) has a value of “Tuesday”. We need not restrict ourselves to string values in arrays – Boolean, numerical and string values are allowed, as in arrays. It is even possible to assign other arrays to array elements – more on this later.

o       The most often-used way of creating an array is to use “square bracket” notation. Square brackets play a large role in the use of arrays, so this is often the easiest method to remember: 

 arrDays = [“Monday”,”Tuesday”];

This is identical to the previous example.

To access an array’s elements, we first call the array’s name, and then specify the number of the element in square brackets, like so: 

 alert(arrDays[0]);

Note the lack of quotes around the 0 here. This line of code is equivalent to:

 alert(“Monday”);

assuming the array is defined as in the previous examples.

o       Not only can we access the value of an array element using this notation, but we can also assign the value as we

arrDays[2] = “Tuesday”; arrDays[3] = “Wednesday”;

o   If you wish to add an element to an array without knowing the index of the last element, you can use the following code:

arrDays[] = “some other day”;

o       As we will see, arrays are actually just special JavaScript objects, and have properties and methods associated with them. The most important property that every array has is its length property:

how_many_days = arrDays.length;

o       As well as properties, arrays have very useful methods. If you wished to sort your array alphanumerically, you could use the array’s sort method thus:

         arrDays.sort();

Note that the sort method works on the actual array itself, overwriting the current values. So, if you had an array with each day of the week as an element, calling its sort method would mean that arrDays[0] was then equal to “Friday”, not “Monday”.

Project

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

Clear all JavaScript code from your script tags.

o   Write a few JavaScript statements that will present the months of the year on the page in alphabetical order. You should use the following technique to achieve this:

o   Store the names of the months of the year in an array.

Use an array method to sort the array elements alphanumericall

o   Use a for loop to iterate through each array element in turn, and print the value of the element to the screen (hint, consider the use of array[i], where i is the for loop’s counter).

o   The above method (the use of a for loop to iterate through a series of array elements) is one of the first common programming techniques we have discussed in this course. Its usefulness cannot be overstated, as it allows us to perform repetitive tasks on a series of related elements without necessarily knowing what those elements might be when we wrote the code. It can be applied to form elements, cookies, page elements, pages, windows, and just about any other collection of object that you might wish to manipulate with JavaScript.

o   To reinforce this generalism, if you have not used the array.length value in your loop, consider its use now. To prove that you have created a more generic loop, try the code with an array of days instead of an array of months, and see if you have to change any of the looping code.

Read More