o The screen object provides you with access to properties of the user’s computer display screen within your JavaScript applications.
o Some of the available properties are:
Property
Description
availHeight
The pixel height of the user’s screen minus the toolbar and any other permanent objects (eg the Windows Taskbar)
availWidth
As availHeight, but dealing with horizontal space
colorDepth
The maximum number of colours the user’s screen can display (in bit format, eg 24 bit, 16 bit etc)
height
The true pixel height of the user’s display
width
The true pixel width of the user’s display
o The left and top parameters of the open() method enable you to specify the position of a window on screen by specifying the number of pixels from the left and top of the screen respectively.
o If you need to use a variable to specify the value of a parameter in the open() method, you would do so as follows:
Where var_left and var_top are the appropriate variables.
o Note the use of the + operator to ensure that the third parameter in the open() method remains as one string when variables are added.
o In order to centre the window on the user’s screen, a little simple geometry is required. The centre of the screen is obviously the point found when we take the width of the screen divided by two, and take the height of the screen divided by two. However, if we set the window’s top and left values to these coordinates, the top left corner of the window will be centred, not the window itself.
o In order to centre the window, we need to subtract half of the window’s height from our top value, and half of the window’s width from our left value. A simple script to accomplish this is as follows:
win_width = 200; win_height = 200;
win_left = (screen.availWidth/2)– (win_width/2);
win_top = (screen.availHeight/2)– (win_height/2);
o By using this script, the values of win_left and win_top will be set correctly for any window using win_width and win_height appropriately to be centred on the screen.
Project
o Open your previous project file, and save it under the name chapter_26.html.
o Modify your existing code to ensure that the logo appears centred on the user’s screen. If possible, do not modify your original function by doing anything more than two new functions – get_win_left( width ) and get_win_top( height ).
o Using standard HTML links, we can open new browser windows:
<a href=”#” target=”_new”>link</a>
o The amount of control this method affords us over the resultant image, however, is nil. We cannot control the size, shape, location on the screen or anything else about that window with this method.
o JavaScript allows us much finer control, as we may expect:
window.open( page_url, name, parameters );
o As we can see from the above prototype, there are only three arguments that this method can take. However, the parameters argument is actually more complex than we might assume:
”param1,param2,param3,param4…”
since we can use it to add many parameters to the method. Note there are no spaces in the parameter list.
o name is used to give the window an HTML name – so we can use that name to open links into the new window using the “target” method above.
o The return value from the open method is an object variable referring to the newly opened window. In other words, if we open a new window like so:
win = window.open(“page.html”, “”, “”);
we can use the object variable win to alter the new window through JavaScript.
o A practical example – let’s say we want to open a new window 300 pixels high by 400 pixels wide, and display the BBC news page in it. The following code would suffice:
o So far we have seen a very simple example of an image rollover. It is functional and works as desired, but it is lacking in a few finer details.
o Specifically, when we use JavaScript to change the src attribute of an <img> tag, the browser has to load this image from scratch. On our local machine, this will not cause an appreciable delay, but when dealing with a remote server (as we will be on the Internet), this delay can lead to a noticeable “lag”, which can destroy the feeling of a dynamic interface.
o Ideally, we would like to instruct the browser to load any alternate images when it loads the page. This will allow us to ensure that the new images are sitting on the user’s computer, ready to be swapped in and out instantly.
o To do this, we need to look at object variables and object instantiation (or creation). In particular, we need to look at the Image object.
o Each <img> tag on the page has a corresponding Image object in JavaScript. We have looked at ways of manipulating this directly, and have an idea of some of the properties an Image object can have.
o However, we can create Image objects directly in JavaScript, without the need for a corresponding <img> tag on the page. When we create such an object, and set its src property, the browser will load the appropriate file into memory, but will not display the image on the page.
o In other words, we can create “virtual” images that exist within JavaScript, and use these Image objects to store the alternate images for our “real” images.
o To create an Image object (in fact, to create any object), we need to use the following code:
virtual_image = new Image();
o We have seen this sort of syntax before – the use of the new keyword when we created our Arrays. new tells JavaScript that we are creating a new object. The virtual_image part of the assignment is just a variable name. In this case, the variable is an Object Variable, since it contains an object.
o To use this variable to preload our images, we take advantage of the fact that it has the same properties and methods as any other image:
virtual_image.src = “contactsover.jpg”;
o The browser will now preload our image, ready to be swapped in at a later time.
Project
o Open your previous project file, and save it under the name chapter_24.html.
o Starting with your previous code, create a new function called preload_images in the head area script element of your page.
o Use this function to create seven new image objects, and use each objects corresponding object variable to preload your “over” image variations.
o Check your work in your browser to ensure that the image swapping still works as expected.
o Add your preload_images function to the body tag of your page to ensure that it runs when the page has finished loading. Use the following syntax:
<body onload=”preload_images();”>
o Once you have verified that the image swapping still works as expected, expand your preload_images function to define an array of images to preload, and then use a for loop to move through the array and assign each image to the src property of an object variable. Hint: an object variable can be anything that can store information – for example an array element.
o A simple image rollover is an effect which happens when the mouse appears over an image (usually a linked button) on the page. The original image is replaced by another of equal size, usually giving the effect that the button is highlighted in some way.
o With what we have learned so far, we already have the ability to create a simple image rollover effect. All that remains is to clarify the particulars of the process:
o The page is loaded and the original image appears on the page as specified by the <img> tag’s src attribute.
o The mouse moves offer the image and the alternative image is loaded into place.
o The mouse leaves the image and the original image is loaded back.
o As you may have realised, we are going to use JavaScript to alter the src attribute of the image tag. The best way to think of this is to picture the <img> tag as simply a space on the page into which an image file can be loaded. The src attribute tells the browser which image to load into the space, and so if we change that value, the image will be changed.
o In other words, the id attribute of the <img> tag is naming the “space”, not the image.
o Now, in order to alter the src attribute with JavaScript, we need to tell JavaScript which image “space” we want to alter. We use the id attribute along with the getElementById() method from the last chapter to do this:
button_img =document.getElementById(“button”);
button_img.src = “new_image.jpg”;
o We can directly insert this code into the image’s event handler:
o This is a much cleaner solution, and more importantly we can use this for any images on the page, simply by changing the arguments of our function call. We can also use the function to achieve the “swap back” functionality:
o We can go even further in “cleaning up” our code, though. Because the event handler is being used to alter the object which is experiencing the event (ie, the mouse is moving over the image tag that we are trying to change), we can use the “automagic” JavaScript object this to perform the operation:
o Note a couple of things. Firstly, this has no quotes around it – we are using it like a variable name. Secondly, our function now uses the first argument directly, instead of using it to get the relevant object from the page. We can do that because this is actually an object – it’s an object that takes on the properties and methods of whatever object it is called from, in this case, it becomes equivalent to
document.getElementById(‘button’), although is obviously much shorter!
o Using this has some limitations. For example, if we wanted to change the src attribute of any other image on the page when the mouse moved over “button”, we would be unable to use this, and hence would have to define another function that could take an id as its argument and get the relevant object that way.
Project
o Copy the folder called buttons from the network drive to your project folder. o Open your previous project file, and save it under the name chapter_23.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 body area of your page, create a paragraph containing six image elements. Set the src attributes of the images to load the following files in your copied buttons folder, and give each a sensible id:
o contacts.jpg o home.jpg o people.jpg o products.jpg o quotes.jpg o whatsnew.jpg
o Create a JavaScript function in the head area script element that takes two arguments – an id and a file name. It should alter the src property of the appropriate image object to the file name given.
o Use this function to swap the src attribute of the contacts button to contactsover.jpg when the mouse moves over the image.
o Once you have this working, update the remaining five images with event handlers to swap their src attributes to their appropriate “over” image.
o Add event handlers to all six images to ensure that they return to their original state when the mouse is moved away from them. Check your work in your browser
o Add a new paragraph above the previous one, and add an <img> tag to it to containing the file rocollogo.jpg from the images folder.
o Add a text link to a new paragraph between the two paragraphs. The link should be a “dummy” link (ie use “#” as its href attribute value), but when the mouse moves over it, the image above it should change to show rocollogo.gif.
o Moving the mouse away from the text link should return the logo to its previous state.
o In HTML, we can identify specific elements on the page using an id attribute. For example, to “name” an image, we can use the following code:
<img src=”logo.gif” alt=”” id=”theLogo” />
o To refer to this element in JavaScript, we can now get to it directly by its id value:
document.getElementById(“theLogo”)
o This method will return an object that refers to the given element on the page. If no such element can be found, the method will return false.
o For easier use, we can assign the object found to a variable. For example, to create an object called our_logo in our scripts, we can use the following line of code:
our_logo = document.getElementById(“theLogo”);
o The resultant object has a number of properties. Since, in this case, our object represents an image element, its properties include:
our_logo.height our_logo.width our_logo.src
o We can use JavaScript to change any of these properties, so if we wanted to change the image displayed, we could do so as follows:
our_logo.src = “new_logo.gif”;
Project
o Copy the folder called images from the network drive to your project folder.
o Open your previous project file, and save it under the name chapter_22.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 body area of your page, create an image element that loads an image from the images folder. Give the element an appropriate id attribute.
o In the head area script element, define a function called describe_image() that will pop up an alert box containing the following information about your image:
the image file used
the image width
the image height
o To have each bit of text appear on a separate line, you can add the following character to your alert text:
for example
alert(“line one Line two”);
o Load your page in the browser and view the results.
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…
onload
An element is loaded on the page
onunload
An element is not loaded, for example when a user leaves a page
onmouseover
When the mouse pointer enters the area defined by an HTML element
onmouseout
When the mouse pointer leaves the area defined by an HTML element
onclick
When 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
onmouseup
When 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:
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.
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 x 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 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_messagereturns 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.
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?”,””);
// 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:
Method
Behaviour
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.
Recent Comments