Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

JAVASCRIPT FOR Beginners, Study notes of Computer science

Learning JavaScript with ease... Bringing the basics of JavaScript into understandable form..

Typology: Study notes

2020/2021

Uploaded on 08/07/2021

i-am-a-develoeper
i-am-a-develoeper 🇳🇬

1 document

Partial preview of the text

Download JAVASCRIPT FOR Beginners and more Study notes Computer science in PDF only on Docsity! JavaScript for Beginners Course notes JavaScript for Beginners 2 10 11 12 13 What is a Programming Language? Key Points .. Server-side vs. Client-side Key Point About JavaScript ..... Key Points .. A Tour of JavaScript 13 Key Points Project... Objects, Properties and Methods Key Points .. Assigning Values to Properties Key Point Project... 25 About Comments Key Point Project... Hiding Scripts from Older Browsers. Key Points .. Project... Automatically Redirecting the User..... Key Points Project... Alert, Prompt and Confirm Variables and Operators.. Key Points Project... Comparisons Key Point Project... Conditionals . Key Point Project... Project JavaScript for Beginners 1 What is a Programming Language? Key Points ° A programming language is a set of codes that we can use to give a computer instructions to follow. Popular and well-known programming languages include Java, C++, COBOL, BASIC, LISP and more. Most popular programming languages consist of words and phrases that are similar in form to the English language. A well-written program will be easily readable by anyone with a little programming experience, regardless of whether they have any direct experience of the language in question. This is because modern programming languages share a large number of common concepts. In particular, they all have a notion of variables, arrays, loops, conditionals, and functions. We will meet these concepts again in more depth later in the course. Traditionally, programming languages have been used to write (for the most part) “stand-alone” applications. Things like Microsoft Word, Mozilla Firefox and Lotus Notes are all examples of such applications. Once installed on a PC, these applications run without necessarily requiring any other software to be installed alongside them. Web Applications differ from these traditional applications in many respects, but the most striking is that they all run inside your web browser. Examples of popular web applications are things like Google, Hotmail, Flickr, GMail and any of the vast array of “weblogging” systems. JavaScript for Beginners o These applications are also written using programming languages, but as a rule they are built using multiple, interdependent technologies. These technologies are easily (though not completely) broken down into two categories: server-side and client-side. JavaScript for Beginners 2 Server-side vs. Client-side Key Points ° The World Wide Web is built on a number of different technologies. For most users, the web starts and ends with their choice of web browser. The browser is said to define the client-side of the web, with the browser, the computer it is running on, and the user surfing the web being collectively referred to as the client. Consider a client who has decided to visit the web site at www.google.com. The first thing that happens is that the client will make a request to Google’s web server for the default page of that web site. The web server is an application running on a computer owned by Google. Like the client, the server application and the computer on which it runs define the server-side of the web, and are collectively referred to as the server. When the server receives the request from the client for a particular page, its job is to retrieve the page from the computer’s files and serve it back to the client. In many cases, this operation is a very simple procedure involving little or no work on the part of the server. However, using a programming language like PHP, Perl or Java, we can cause the server to either modify the page it finds before it passes it back to the client, or even to generate the page entirely from scratch. This is referred to as a server-side application. The page passed back to the client looks (to the client) exactly the same as any other page that has not been modified. JavaScript for Beginners 10 3 About JavaScript Key Points o JavaScript is an interpreted, client-side, event-based, object- oriented scripting language that you can use to add dynamic interactivity to your web pages. o JavaScript scripts are written in plain text, like HTML, XML, Java, PHP and just about any other modern computer code. In this code, we will use Windows NotePad to create and edit our JavaScript code, but there are a large number of alternatives available. NotePad is chosen to demonstrate JavaScript’ s immediacy and simplicity. o You can use JavaScript to achieve any of the following: = Create special effects with images that give the impression that a button is either highlighted or depressed whenever the mouse pointer is hovered over it. = Validate information that users enter into your web forms = Open pages in new windows, and customise the appearance of those new windows. = Detect the capabilities of the user’s browser and alter your page’s content appropriately. = Create custom pages “on the fly” without the need for a server-side language like PHP. = And much more... JavaScript for Beginners “1 o JavaScript is not Java, though if you come from a Java background, you will notice that both languages look similar when written. Java is a full featured and comprehensive programming language similar to C or C++, and although JavaScript can interact with Java web applications, the two should not be confused. o Different web browsers will run your JavaScript in different, sometimes incompatible ways. In order to work around this, it is often necessary to use JavaScript itself to detect the capabilities of the browser in which it finds itself, and alter its operation depending on the result. o Torevisit the original definition in this chapter, note the following points: = Interpreted refers to the fact that JavaScript code is executed (acted on) as it is loaded into the browser. This is a change of pace from compiled languages like Java, which check your program thoroughly before running a single line of code, and can have many implications that can catch you out if you are from a non-interpreted programming background. = Client-side has been defined already in the previous chapter. = Event-based refers to JavaScript’s ability to run certain bits of code only when a specified event occurs. An event could be the page being loaded, a form being submitted, a link being clicked, or an image being pointed at by a mouse pointer. = Object-oriented signals that JavaScript’s power to exert control over an HTML page is based on manipulating objects within that page. If you are familiar with object-oriented programming, you will be aware of some of the power that this can bring to the coding environment. JavaScript for Beginners 12 o One final note: While JavaScript is a programming language, HTML (the language of the World Wide Web) is not. HTML is a Markup Language, which means that it can be used to mark areas of a document as having special characteristics like headers, paragraphs, images, forms and so on, but it cannot perform any logical processing on its own. So while JavaScript is often written alongside HTML, the rules of one do not necessarily have any bearing on the other. JavaScript for Beginners 15 o 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 ow JavaScript. o Go back to NotePad and enter the following text between the opening and closing script tags: window.alert(“Hello world!”); o Save your changes, and again refresh your page in the browser window. Welcome to the world of JavaScript! o 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/"; } } JavaScript for Beginners 16 o 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 acommon HTML trick that allows us to create a “dink 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! JavaScript for Beginners 47 o 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. JavaScript for Beginners 20 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 Inmany 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. JavaScript for Beginners 21 6 Assigning Values to Properties Key Points ° 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 the user, 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. 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”); 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. A much more direct way to solve this problem is to access the object’s properties directly. For example: piano.colour = “green”; 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. JavaScript for Beginners 22 Project 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”; There are many assignment operators in JavaScript. Some of the more common are shown in the table below: Assignment Function x=y Sets the value of x toy xt=y Sets the value of x to xty x-=y Sets the value of x to x-y x *y Sets the value of x to x times y xy Sets the value of x to x divided by y 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. Open your previous project file, and save it under the name chapter_6.html. Remove any existing JavaScript from your script tags, but leave the tags in place ready for some new JavaScript. JavaScript for Beginners 25 7 About Comments Key Points ° Repeat after me : Comments are important. Comments are important. Comments are important. 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. 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. Comments are completely ignored by JavaScript and have no effect on the speed at which your scripts run, provided they are properly formed. 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. There are two types of comment in JavaScript — single line comments, and multi-line comments. Single line comments begin with two forward-slash characters (//), and end with a new line: // this is a comment alert(“hello”); // so is this JavaScript for Beginners 26 Project Single line comments in JavaScript can also use the HTML comment format that you may be familiar with: <!-- this is a comment alert(“hello”) ; 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. 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 */ 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!”); 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. Open your previous project file, and save it under the name chapter_7.html. Add the single line comment This is my first comment to the beginning of your script. JavaScript for Beginners 27 o Adda multi-line comment to your script, replacing your previous single line comment. The multi-line comment should describe what your script does at present. JavaScript for Beginners 30 o Add anoscript element to explain what your JavaScript does. Itis 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. JavaScript for Beginners 31 9 Automatically Redirecting the User Key Points o We have already briefly seen the use of browser redirection in Project chapter 4. 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. As we saw in chapter 6, we can use the assignment operator here. For example: document .locat ion document .locat ion “http: //www. bbc.co. uk/"; “chapter_4.htm1"; Open your previous project file, and save it under the name chapter_9_ redirect .html. Save another copy of the file, this time called chapter_9.html. Make sure both files are saved in the same folder, and that you have chapter_9.html open in your editor. 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. 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. JavaScript for Beginners 32 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. o Experiment with various positions for the script tags on chapter_9.html to see if you can make the header appear before the redirection. JavaScript for Beginners 35 1 1 Variables and Operators Key Points ° We have been introduced to the concepts of objects and their various properties and methods. These inter-related concepts allow any web page to be broken down into little snippets of information or data, which can then be accessed by JavaScript and, in many cases, changed. However, what if we want to create our own storage space for information that doesn’t necessarily have a page-based counterpart? For example, what if we wanted to store the previous value of a document’s title property before changing it, so it could be retrieved later, or if we wished to store the date time that the page was loaded into the browser for reproduction in several places on the page, and didn’t want to have to recalculate the time on each occasion? Variables are named containers for values within JavaScript. They are similar to object properties in many ways, but differ importantly: Ina practical sense, variables have no “parent” object with which they are associated. Variables can be created (“declared”) by you as a developer, and can be given any arbitrary name (within certain rules) — object properties, however, are restricted by the definition of the parent object. It would make no sense, for example, for our piano object in the previous chapters to have a propeller property! JavaScript for Beginners 36 o Variable name rules are straightforward — no spaces, names must start with a letter. Examples of valid variable names are: BrowserName page_name Messagel MESSAGE1 o Inmany browsers, JavaScript is case-sensitive, which means that the last two variables in the example above are distinct variables. It is a good idea to pick a particular naming style for your variables, and to stick to it within your projects. o At the simplest level, variables can store three different types of value: o Numbers e.g. 1.3324, 3.14159, 100000, -8 etc. o Strings e.g. “JavaScript for Beginners, week 3”, “Hello World” etc. o Boolean Values e.g. true, false o Note that strings can contain numbers, but the following variable values are not equivalent: 1.234 and “1.234” The latter is a string value. This becomes important. Consider: 1+2=3 kg? $b” = “ah? ey 4 eg = 9” o Some developers use their own naming convention with variable names to denote the type of value expected to be contained in a given variable. This can often be helpful, but is in no way required by JavaScript (c.f. JavaScript comments) o For example, strMessage might indicate a string variable, where numPageHits might indicate a numerical value in the variable. JavaScript for Beginners 37 o Variable assignment is accomplished in the same way as object property assignment. When a variable is assigned a value for the first time, it is automatically created. This is different from other programming languages, where a variable must be created explicitly first, before it can be loaded with a value. o Some examples of variable assignment follow: numBrowserVersion = 5.5; nunfotal += 33; Message = “Hello!”; Message “Goodbye”; Message = 3; o Note that the last three examples show that variable values can be altered after their initial assignment, and also that the type of value stored ina variable can be altered ina similar manner. o Oncea variable has been created and a value stored within, we will want to be able to access it and perhaps manipulate it. Ina similar manner to object properties, we access our variables simply by calling them: Message = “Hello World!”; alert (Message) ; o Note that we do not use quote marks around our variable names. The above code is different from: alert(“Message”); for hopefully obvious reasons. o As well as using variables for storage and access, we can combine and manipulate them using operators. For example: 12; 13; a+b; // c¢ is now 25 += a; // c is now 37 = b+” Hello!”; // c is now “13 Hello!” anaagva Wl JavaScript for Beginners 40 1 2 Comparisons Key Points 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_l = 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”: false; // Boolean value “false”; // Text string var_4 var_5 o Common comparison operators are given below: Comparison Function xX=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 JavaScript for Beginners u X>=y Returns true if x is numerically greater than or equal to y, false otherwise X<y Returns true ify is numerically greater than x, false otherwise X<=y Returns true ify is numerically greater than or equal to x, false otherwise o To reverse the value returned from a comparison, we generally Project modify the comparison operator with a ! (a “bang”). Note that in many cases this is not necessary, but can aid comprehension: var_l !> 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. Open your previous project file, and save it under the name chapter_12.html. Ensure that your two variables both have numerical values in them and not strings. Use an alert box to display the result of a comparison of your two variables for each of the comparison operators listed above. Substitute one of the numerical values for a text string and tepeat the procedure. Note the differences. JavaScript for Beginners 42 1 3 Conditionals Key Points ° 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. 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. 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. Conditional statements give us that ability, and are key to working with JavaScript. A conditional statement consists of three parts: A test (often with a comparison operator, or comparator) to see if a given condition is true or false. A block of code that is performed if and only if the condition is true. An optional block of code that is performed if and only if the condition is false. JavaScript for Beginners 45 ° Project 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. Consider the following block of code: if ( var_l>4) { var_2 = var_l; } else { var_2 = 4; } This code is rather long, but achieves comparatively little — var_2 is equal to var_1 or 4, whichever is greater. A more compact way of writing this could be: var_2 = 4; if ( var_1 > var_2 ) { var_2 = var_l; } However, an even more compact way of writing this could be to use the ternary operator: var_2 = (var_l > 4) ? var_l: 4; In the above statement, the conditional is evaluated and, if true, the value returned is the value between ? and : symbols, or if false, it is the value between the : and ; symbols. Open your previous project file, and save it under the name chapter_13.html. Clear all JavaScript code from your script tags. Create two variables and assign numerical values to them. JavaScript for Beginners 46 o Usea conditional statement to show alert boxes declaring which variable is the greater of the two. o Consider the following code: var_3 = (var_l > var_2); o Use this code in your script to simplify your conditional checking code. o Now, use a prompt box to ask your visitor their name. Assign this name to var_3. o Check to see if the name typed in is your own name. If it is, use document .write to display a personalised greeting on the page. Otherwise, display a generic greeting. o Use multiple else if branches to check the typed name against the names of some of your friends. Create personalised messages for all of them. o There may be a way to simplify your conditional greeting code to use only one document.write statement. See if you can figure out how. Hint — how might you use a variable called greeting? Project 2 o Inmany cases, the brevity of your conditional statements will tely on your ability to formulate the right “questions” to consider when performing your tests. Try to make your solution to the following problem as concise as possible. o Clear all of your cwrent code from the script tags. o Ensure that your script tags are currently situated in the body section of the page. o Create a variable called exam_result and store a numerical value of between 0 and 100 init. JavaScript for Beginners 47 o Use an if statement and multiple else if statements to check the value of this variable against the following exam grading scheme, and print out the appropriate message to the page: Exam Result Result Message 90 or more Excellent. Pass with Distinction. Between 70 and 89 Well Done. Pass with Honours Between 55 and 69 Just passed. 54 or below Failed. Do better next time. o Test your result in your browser. Vary the value of exam_result and check the value shown in the browser. For extra practise, try to use a prompt box to make changes to your exam_result variable as easy to achieve as possible. JavaScript for Beginners 50 Project The for statement tells the browser that we are about to perform a loop. The layout here is very similar to a conditional statement, but in this case we have much more information in the brackets. Where our conditional had one JavaScript statement to describe its action, a for loop has three: An initialiser — this sets up the initial counting condition, in this case i = 1. A conditional — this is identical to our conditional statements earlier, and must return true or false. If it returns true, the loop continues, otherwise it exits. An incrementer — this defines the action to be performed at the end of each loop. In this case, i is incremented by a value of 1. The key difference between a conditional and a for loop is that the condition is constantly being changed and re-evaluated. It is possible to create an infinite loop by making the conditional non-reliant on the count value — for example: for ( i=0; 5 > 4; itt+ ) will always perform the script in the braces, and will probably cause errors in the browser. Note too that it is very common to start counting at zero in JavaScript. The reason for this is that it is often desirable to count how many times an operation has been performed. Consider the following: for ( i=1; 1 < 2; it+ ) In this case, the loop will run once, but the value of i will be 2, as after the first run, i will be incremented to 2, and will then fail the test and so the loop will exit. If we use the following: for ( i=0; 1 < 1; it+ ) Then the loop will run once, and the value of i afterwards will be 1, as we might hope. Open your previous project file, and save it under the name chapter_14.html. Clear all JavaScript code from your script tags. JavaScript for Beginners 51 o White a series of statements to produce a multiplication table as follows: The 12x Multiplication Table 1x 12=12 2x 12=24 3x 12=36 4x 12=48 5x 12=60 6x 12= Txt 8x 12=96 9x 12=108 10x 12=120 11x 12=132 12x 12= 144 o The following exercise is more of an HTML example, but demonstrates an important facet of using JavaScript (or, indeed, any programming language) to produce well-formatted text. o Modify your previous code to make your page’s content appear in the centre of the page. Put your multiplication table in an HTML table to make sure that the equals signs, multiplication signs and so forth line up in neat columns: The 12x Multiplication Table 6x 12=72 7x 12=84 8x 12=96 JavaScript for Beginners 52 o Asa hint, here is a look at the table cells involved: The 12x Multiplication Table (Dials JavaScript for Beginners 55 o 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 well: arrDays[2] arrDays[3] “Tuesday”; “Wednesday”; o Ifyou 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, over- writing 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. JavaScript for Beginners 56 o 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. o Use an array method to sort the array elements alphanumerically. o Usea 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 tepetitive 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 Toreinforce 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. JavaScript for Beginners 57 1 6 Associative & Objective Arrays Key Points o We have already seen that we can access array elements by their index: arrDays = [“Monday”, “Tuesday” ]; // print “Monday” to the page document .write (arrDays [0]) ; o However, it might be more useful to be able to name our array elements. By default, an array will be created as a numeric array. We can also create an associative array: arrDays = new Array(); arrDays[“Monday”] = “Go to the dentist”; arrDays[“Tuesday”] = “Attend JavaScript class”; arrDays[“Wednesday”] = “JavaScript homework”; // remind you of Wednesday's task alert (arrDays[ “Wednesday”] ); o This looks a lot like our previous discussion of objects and properties. In fact, since an array is actually an object, we can access its elements as though they were properties: // remind you of Wednesday's task alert (arrDays.Wedensday) ; JavaScript for Beginners 60 Project Similarly, we can happily use our “objective” notation for associative arrays: alert(array_3.secondArray[3]); //displays “98" yet again Open your previous project file, and save it under the name chapter_17.html. Building on your previous project, create a number of new, seven element associative arrays to represent 4 separate weeks. Combine these 4 weeks into a four element array to represent a month. Modify your previous code to take a week number and print out all that week’s activities to the page. Modify one of your week arrays to consist not of single elements, but of arrays of hours from 8am to Spm. This then tepresents a three dimensional array. We can extend arrays to be n-dimensional, where n is more or less arbitrary. Finally, alter your code to prompt the user for three values — a week, a day and an hour. Store these values in three separate variables, and use those variables to display the requested task, or else to display an error message if a task cannot be found. JavaScript for Beginners 61 1 8 String Manipulation Key Points ° 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. We have already seen some basic string reading in the section on comparisons where we test for equality. However, this all- or-nothing approach is often not subtle enough for our purposes. 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. 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. 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_l var_2 “Karen Aaronofsky” ; var_l.indexOf(“Karen”) ; In this case, the value of var_2 will be 0 —remembering that JavaScript begins counting at 0! JavaScript for Beginners 62 o If we were to search for a surname here: var_1l = “Karen Aaronofsky”; var_2 = var_1l.indexOf( “Aaronofsky” ); 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 Inorder 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 = “Karen”; name = prompt( “Your name?”,""); real_name = real_name.toLowerCase(); try_name = try_name.toLowerCase(); if ( try_name. indexOf(real_name) > -1 ) alert(“Hello Karen!”); } 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: Method Behaviour String. indexOf(‘st”) 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 JavaScript for Beginners 65 o The following code checks a variable to see ifit looks like an email address: var_l = prompt (“Your email?”, “"); if ( var_1l.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 Usea 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 Inthe latter case, output the failed string as well so that the user can see their input and modify it next time, if appropriate. JavaScript for Beginners 66 1 9 Using Functions Key Points ° 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. JavaScript functions are declared before they are used. The declaration looks like this: function name_of_function( ) { «your code here... } Unlike all the JavaScript instructions we have looked at so far, the code inside a function will not be run until specifically tequested. Such a request is called a function call. 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. 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_funct ion function above, we would use the following line of code: name_of_function(); JavaScript for Beginners 67 o 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_l = 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_l = false; if ( address.match(/*.+@.+\..+$/) ) { var_l = 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. JavaScript for Beginners 70 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 teplacing 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. JavaScript for Beginners a 2 0 Logical Operators Key Points co Inour discussion of conditionals, we saw how to check the veracity of a single condition via a comparator: if ( x > some_value ) { ..e@xpress ions... } o We have also seen the limitations of such an approach. Let us say we wanted to discover ifx lay between two values, say val_1i 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_l ) { «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 va1_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. JavaScript for Beginners 72 o InEnglish, 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 3" 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 3" day of the month. o Note in the last example, if both conditions were true, then we would be on Tuesday the 3" and would perform the action. In other words, an or condition allows for either one, or the other, or both conditions to be true. JavaScript for Beginners 75 2 1 Using Event Handlers Key Points ° 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. 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. 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. 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. 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. Some common event handlers are in the table below: Event Handler Occurs When... onload An element is loaded on the page JavaScript for Beginners 76 onunload An element is not loaded, for example when auser 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 Intheory, 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. co To attach an event handler to a tag, we use the following method: <a href="..” onclick="a_function();”>Link</a> o Wecan 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> JavaScript for Beginners 7 Project 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. Open your previous project file, and save it under the name chapter_21.html. Clear all JavaScript code from your script tags. Ensure that you have a script element in the head area of your document, and none in the body area. Within the head area script element, define the following function: function set_status( msg ) { window.status = msg; } 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”); Now define the following function immediately below the last: function clear_status( ) { set_status(“"); } 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. 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="#" J onmouseover="set_status(‘hello’);" 4 onmouseout="clear_status();”>testing</a> JavaScript for Beginners 80 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: \n for example alert(“line one\nLine two”); o Load your page in the browser and view the results. JavaScript for Beginners 81 23 Simple Image Rollovers Key Points 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 sre attribute tells the browser which image to load into the space, and so if we change that value, the image will be changed. o Inother words, the id attribute of the <img> tag is naming the “space”, not the image. JavaScript for Beginners 82 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 getElementByIdQ method from the last chapter to do this: button_img = ./ document .getElementById( “button” ) ; button_img.sre = “new_image. jpg”; o Wecan directly insert this code into the image’s event handler: <img src="o0ld.jpg” id="button” J onmouseove r=,]| "document. getElementById(‘button’).sre .| = 'new.jpg’;"> o Note that this code is suddenly very convoluted. There are two immediate potential solutions. The first is to define a function: function swap_image( id, new_image ) { img = document.getElementById( id); img.src = new_image; } <img src="old.jpg” id="button” J onmouseover= ,| "swap_image(‘button’, ‘new.jpg’);"> 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: <img src="old.jpg” id="button” JJ onmouseover= ,| "swap_image(‘button’, ‘new.jpg’);” <| onmouseout= | "swap_image(‘button’, ‘old.jpg’);"> JavaScript for Beginners 85 24 Object Instantiation and Better Rollovers Key Points ° So far we have seen a very simple example of an image rollover. It is functional and works as desired, but it is lacking ina few finer details. Specifically, when we use JavaScript to change the sre 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 “ag”, which can destroy the feeling of a dynamic interface. 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, teady to be swapped in and out instantly. 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. 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. 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. JavaScript for Beginners 86 Project 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. To create an Image object (in fact, to create any object), we need to use the following code: virtual_image = new Image(); 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. 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”; The browser will now preload our image, ready to be swapped inat a later time. Open your previous project file, and save it under the name chapter_24.html. Starting with your previous code, create a new function called preload_images in the head area script element of your page. Use this function to create seven new image objects, and use each objects corresponding object variable to preload your “over” image variations. Check your work in your browser to ensure that the image swapping still works as expected. 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() ;"> JavaScript for Beginners 87 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 sre property of an object variable. Hint: an object variable can be anything that can store information — for example an array element. o Check your work in your browser. JavaScript for Beginners 90 Project However, if any parameter is set, all others default to “no”. So if you wanted to have a scrollbar but nothing else, the following would suffice: window.open(“http://www.bbc.co.uk/", | “bbe”, “scrollbars=yes”); Open your previous project file, and save it under the name chapter_25.html. Remove all functions and HTML from your previous file, leaving only the logo image and the link. Create a function in the head area script element called view_new_logo. This function should: = Open a new window 200 pixels square. = Load the image rocollogo. jpg from the images folder. = Be called Rocol Logo = Be stored in an object variable called obj NewLogo. = Have no scrollbars, be of a fixed size, and have no other features where possible. Remove all event handlers from the link, and add a new one to run the function above when the link is clicked. Once you have verified that a window pops up as required when the link is clicked, test each parameter from the table above in the function. JavaScript for Beginners 91 2 6 Positioning Browser Windows Key Points 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 availHeight availWidth colorDepth height width Description The pixel height of the user’s screen minus the toolbar and any other permanent objects (eg the Windows Taskbar) As availHeight, but dealing with horizontal space The maximum number of colours the user’s screen can display (in bit format, eg 24 bit, 16 bit etc) The true pixel height of the user’s display 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 Ifyouneed to use a variable to specify the value of a parameter in the open() method, you would do so as follows: window.open(“index.html”, “window_name”, | “width=200 ,height=200, left="+var_left+ .| “top="+var_top); Where var_left and var_top are the appropriate variables. JavaScript for Beginners 92 Project Note the use of the + operator to ensure that the third parameter in the open () method remains as one string when variables are added. 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. 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); 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. Open your previous project file, and save it under the name chapter_26.html. 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 ). JavaScript for Beginners 95 28 Dynamically Created Content Key Points ° Project It’s quite easy to create a new page on demand using JavaScript. In this context, we are talking about creating a completely new page in a window without loading any file into that window. To do this, invoke the open() method of the window object, leaving the location parameter empty: new_win = window.open(“”, “newWin”, | “params...”) ; Next, remember that you can write HTML code toa page using the window’s document .write() method. Up until now, we have used only the current window’s document object. However, we can specify which window’s document we want to manipulate as follows: document.write(); // write to current window new_win.document .write(); // or new window For example: new_win. document .write (“<html><head>”) ; new_win. document .write (“<t itle>demo</title>"): new_win. document .write (“</head><body>") ; new_win. document .write (“<h1>Hello!</h1>") ; new_win. document .write (“</body></html1>" ); Open your previous project file, and save it under the name chapter_28.html. JavaScript for Beginners 96 o Modify your existing script to create a third window with the following properties: The window should be called newHTML, and be assigned to the object variable objNewHTML. It should be 400 pixels square. It should not load any page when it is created. It should display the word “Welcome” as an 1 header. It should contain a paragraph with the text “Please decide which logo you would like to choose.” The third window should carry the title “Rocol Art” When all windows have been opened, the third window should be focussed. o Check your work in the browser. JavaScript for Beginners 97 29 Working with Multiple Windows Key Points ° The window object’s close() method enables you to close a window. If you have an object variable in the current window teferring to the window you wish to close, you can simply use: new_window.close() ; to close the window. Things are a little more complicated when you wish to close a window from a window other than the one which opened the new window. In order to tackle this, we need to think about window scope. When we write JavaScript into our code, all functions and variables within that script are available for us to use within that window. For example, if we have a function called say_he11lo() in ow main window, we can easily call that function. However, if we want to call the function from a newly opened window, we cannot call it directly from the new window, as our functions and variables are “tied” to the windows in which they were first defined. This is why, when we want to write to any window other than the one containing our JavaScript code, we must access the document object of that window in order to put content in the tight place, But how about in the other direction? Let’s say we use a function in our main window (call it window 1) to open a new window (window 2). If we store window 2 as an object variable, we can access all properties of window 2 from window 1 by using that object. The question is, how do we access any properties of window 1 from window 2?
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved