450 likes | 557 Views
269200 Web Programming Language. Week 4 Dr. Ken Cosh Introducing Javascript. Recap. We’ve been looking at “Front End” development Using HTML & CSS to make the page look the way we want CSS for style CSS for layout. Javascript. Enables Dynamic Functionality
E N D
269200 Web Programming Language Week 4 Dr. Ken Cosh Introducing Javascript
Recap • We’ve been looking at “Front End” development • Using HTML & CSS to make the page look the way we want • CSS for style • CSS for layout
Javascript • Enables Dynamic Functionality • Pop Up when your mouse goes over it • Updates Page • Move objects around page • Browser side Scripting language • Runs in the browser • Has access to all elements in the document
<script></script> Alternative is VBScript C++ Style Dot Notation No Semicolon • <script type=“text/javascript”> • document.write(“Hello World”) • </script>
Where to Javascript? • In the Body • In the Head • In a .js file • <script type=“text/javascript” src=“script.js”></script>
Debugging • Use the Console! <script> a = 5; b = 6; c = a + b; console.log(c);</script> • Be aware, that not all browsers will give the same console error message!
Comments // This is a comment! /* This is a longer set of comments Seem familiar? */
Semi Colons • Semi colons are not necessary, unless you want to put more than one statement on a line; • X +=10; y-=5; z=0 • A new line terminates any statement • But you can use semicolons if you like
Variables • Weakly Typed Language • Name can include a-z, A-Z, 0-9, $ and _ • First character is not a number • Case Sensitive
Strings • Surrounded by “ or ‘ • If necessary escape another quote using \ • Message = ‘Hi I\’m Ken!’ • A string can be assigned another strings value; • stringa = stringb
Operators • Arithmetic Operators • +, -, *, /, %, ++, -- • Assignment Operators • =, +=, -=, *=, /=, %= • Comparison Operators • ==, !=, >, <, >=, <=, === (equal to and of the same type), !== • Logical Operators • &&, ||, !
String Concatenation • Uses the + symbol Name = “Ken” + “Cosh”
Types • JavaScript is Loosely Typed • The type is determined when a value is assigned to it, and the variable’s type can change
Functions <script> function sum(a, b) { return a + b } </script>
The DOM • Document Object Model • Different parts of the HTML are discrete objects • And each object has its own properties and methods • The dot notation is used to refer to properties or methods of an object
The DOM A URL is the href part of an anchor tag somewhere in the document; <html> <head> <title> Link Test</title> </head> <body> <a id=“mylink” href=http://www.kencosh.com>Click Here</a><br> <script> url = document.links.mylink.href document.write(‘The URL is ‘ + url) </script> </body> </html> (Note, this probably won’t work in IE!)
links • links is an array of the links with in document, so we could reference it as; url=document.links[0].href • We could find the size of the links array using numlinks = document.links.length • So, we could do; for(i=0; i<document.links.length; i++) document.write(document.links[i].href + ‘<br>’)
length • length is a property of all arrays • Including the history object, which contains a list of urls that the browser has visited. document.write(history.length) • The history object has some functions, for example; history.go(-3) //Go back 3 pages history.back() history.forward()
getElementById • A useful function is ‘getElementById’, which takes as its parameter the id given to a tag; url = document.getElementById(‘mylink’).href • Because ‘getElementById’ is SO important, often it is replaced by the function ‘$’, so we could use; url = $(‘mylink’).href
$ <script> function $(id) { return document.getElementById(id) } </script>
If Statement if(a > 100) { document.write(“a is greater than 100”) } else if(a<100) { document.write(“a is less than 100”) } else { document.write(“a is equal to 100”) }
Switch Statement switch(page) { case “Home”: document.write(“You selected Home”) break case “About”: document.write(“You selected About”) break case “Links”: document.write(“You selected Links”) break }
The Ternary Operator (?) ? can used instead of if statements document.write(a <= 5 ? “a is less than or equal to 5” : “a is greater than 5”)
While Loops while (counter <5) { document.write(“Counter: “ + counter + “<br>”) ++counter } What would happen without ++counter ?
Do … While count = 1 do { document.write(count + “ times 5 is “ + count * 5 + “<br>”) } while (++count <= 5)
For Loops for(count = 1; count <=5; count++) { document.write(count + “ time 5 is “ + count * 5 + “<br>”); }
With string = “The quick brown fox jumps over the lazy dog” with(string) { document.write(“The string is “ + length + “ characters<br>”) document.write(“In uppercase it is: “ + toUpperCase()) }
Arrays • Should be pretty familiar to you; students = [‘John’, ‘Peter’, ‘Mike’]
Multi-dimensional arrays tictactoe = [[‘X’, ‘O’, ‘X’], [‘O’, ‘X’, ‘O’], [‘X’, ‘O’, ‘X’]] document.write(tictactoe[1][2])
Associative Arrays countries = {“uk”: “United Kingdom”, “th”: “Thailand”, “us”: “United States”} for (country in countries) document.write(country + “ = “ + countries[country] + “<br>”)
Array Methods concat – concatenates 2 arrays fruit = [“Banana”, “Grape”] veg = [“Carrot”, “Cabbage”] document.write(fruit.concat(veg))
Array Methods push() pop() reverse() sort()
Defining Functions function function_name(parameters) { statements }
The arguments Array The arguments Array is a member of every function You can use it to find the number of arguments (parameters), and what they are.
Example What if we have more than 5 (or less than 5 items)? displayItems(“Dog”, “Cat”, “Pony”, “Hamster”, “Tortoise”) function displayItems(v1, v2, v3, v4, v5) { document.write(v1 + “<br>”) document.write(v2 + “<br>”) document.write(v3 + “<br>”) document.write(v4 + “<br>”) document.write(v5 + “<br>”) }
Using arguments function displayItems() { for(i=0; i<displayItems.arguments.length; ++i) document.write(displayItems.arguments[i] + “<br>”) }
Returning Values document.write(fixNames(“Kenneth”, “JOHN”, “cOSh”)) function fixNames() { var s = “” for (i=0; i<fixNames.arguments.length; ++i) s += fixNames.arguments[i].charAt(0).toUpperCase() + fixNames.arguments[i].substr(1).toLowerCase() + “ “ return s.substr(0, s.length-1) }
Returning Arrays words = fixNames(“kenneth”, “JOHN”, “cOSh”) for(i=0; i<words.length; ++i) document.write(words[i] + “<br>”) function fixNames() { var s= new Array() for (i=0; i<fixNames.arguments.length; ++i) s[i] = fixNames.arguments[i].charAt(0).toUpperCase() + fixNames.arguments[i].substr(1).toLowerCase() return s }
Exercise – Form Validation Create a Registration Form The form should ask users to input the information to the right You will then need to validate the information that they input.
Exercise – Form Validation Forename – Must not be blank, must not contain spaces, and must have at least 3 alphabet characters Surname – same as for Forename Username – At least 5 characters and can include numbers, _ and – Password – Must be at least 8 characters, containing both upper and lower case letters, numbers and symbols. Age – It is a 18+ website, so the age must be between 18 and 110 Email – must be of the form abc@def.ghi
Impress Me! How about re-entering password to make sure it is the same? How about making it look good with css? How about indicating the required fields with a * - and have the star disappear when the entry is ok? How about date of birth with a calendar, rather than age? How about storing your js functions in a separate .js file?
But First… HTML Forms Forms can be used to pass data from one webpage to another Forms can contain input boxes, drop down menus, check boxes, radio buttons, etc.
HTML Forms To impress me, you might want to look at other input types! <form method=“post” action=“page2.html” onsubmit=“return validate(this)”> Forename: <input type=“text” name=“forename”> </form>