Download presentation
Presentation is loading. Please wait.
1
Understanding JavaScript
2
The Three Layers of the Web
3
What is JavaScript? Lightweight programming language
Adds interactivity to HTML pages Works in all major browsers – IE, Mozilla, Firefox, Netscape, Opera and Safari Is a complementary language – not used on own (embedded into HTML pages) Primarily used for web-related programming Consists of lines of executable code (statements)
4
What is JavaScript? Is an interpreted language (no preliminary compilation) No need to purchase a license Used on the client-side (browser) of web application Is the J in the acronym AJAX (Asynchronous JavaScript and XML) JavaScript is not related to Java (Sun Microsystems)
5
What JavaScript Can Do Gives web designers a programming tool (“code snippets”) Dynamic effects on pages document.write(“<h1>” + name + “</h1>”) Responds to user actions (event-driven) Reads and writes HTML elements Change page appearance – text, background Pop-up windows – alert, confirm and prompt
6
Examples: Flashing grid of coloured squares ( How to change images on a web page How to affect web pages over time How to add randomness to web pages How to dynamically change what’s happening on a web page based on a user action Fish Weight Calculator (
7
What JavaScript Can Do Image swaps and rollover effects
Drop-down menus Performs calculations Opens new browser windows Form entry validation Create cookies Browser detection
8
History of JavaScript Developed by Brendan Eich (Netscape) -1996
Together with Sun Microsystems Appeared in all major browsers since then Microsoft developed its own version – JScript Official name is ECMAScript ( ECMA-262 is the official JavaScript standard
9
JavaScript Guidelines
JavaScript is case sensitive “myfunction” is not the same as “myFunction” “myvar” is not the same as “myVar” JavaScript ignores white space name=“Bedford”; name = “Bedford”; Break up code lines (within strings) document.write(“Hello \ World!”);
10
JavaScript Guidelines
JavaScript once required a semicolon (;) at the end of each statement Group statements together into blocks by enclosing within curly braces { and } Single line comments //This code will write “Hello World” to the page Multi-line comments /*This code will write one header and two paragraphs to the page */
11
Object-Oriented Programming (OOP)
JavaScript uses a model called OOP (object-orientated programming) Objects (for example, a window) Properties (for example, length) Methods or actions (for example, open) Events (for example, click) Note: Many programmers argue the notion that JavaScript uses the object-orientated model.
12
Compiled vs. Intepreted
JavaScript is an interpreted language Code is run on the fly - no need to compile Only need a text editor and browser Does not perform as efficiently as compiled code Easy to edit and embed in a web page Compiled code tends to be platform specific – JavaScript is not
13
JavaScript Statement var smallNumber = 4; Reserved Word Identifier
Operator Literal
14
What JavaScript Can’t Do
JavaScript can’t be forced on a client JavaScript may be disabled in browser JavaScript is not supported in older browsers JavaScript’s fancy features may not be accessible to all – text-readers, text-only browsers, accessibility issues JavaScript can’t cross domains JavaScript can’t ensure data security JavaScript can’t access server data or scripts
15
Beware!! When you develop pages containing JavaScript you have little control over the final appearance or functionality of your page. The script is parsed/interpreted by the browser and the page content displayed according to browser (User Agent) settings and other variables.
16
Remember……… TEST YOUR PAGES IN AS MANY BROWSERS (AND OTHER PLATFORMS) AS POSSIBLE Test in Mozilla Firefox (roots in Netscape), IE and Apple’s Safari DON’T MAKE NAVIGATION OF YOUR WEBSITE DEPENDENT ON JAVASCRIPT!!! ACCESSIBILITY IS A BIG ISSUE!!!
17
Text/Code Editors Simplest is NotePad or MAC version
Better to use a slightly more complex editor Free downloads from Look for Freeware or Shareware Small total file size
18
What to look for… Provide colour coding Assist in entering code
Code indentation Validate syntax Numbered lines Code snippets Debugging tools Code and design views Integrate with other languages – JavaScript, HTML, CSS, Java, ASP, PHP
19
Fundamentals of JavaScript
Using JavaScript with HTML pages Where to put your code Commenting your code Special Characters and Escape Sequences Reserved words
20
Parts of JavaScript Variables and Constants Types of Data
Naming Conventions Operators Statements and Expressions Functions Global Functions User-Defined Functions Objects – Properties, Methods, Event Handlers Control Structures
21
Variables and Constants
Information used in JavaScript falls into one of two categories: Variables: Items that can contain different values at different times during script execution. Start with the keyword var followed by name. Constants: Contain the same value throughout the execution of the script.
22
Types of Data Data Type Name Description Examples Boolean bool
Either TRUE or FALSE and is not case sensitive – but commonly uppercase TRUE, FALSE Numeric/Floating point numbers float A fractional number with a decimal. May be negative and may use scientific notation 7.34, , 2.31e3 Numeric/Integers Int A whole number without a decimal. May be negative 43, 928, -4 Numeric/Null null The absence of any value NULL String string A series of characters (one of 256 letters, numbers and special characters) enclosed in either single or double quotation marks “Mike”, “Seattle”, “1495 W. 18th St.” Undefined A named variable that has not been assigned a value
23
Naming Conventions See later
Beware use of predefined or reserved words when naming variables and constants. Their use will cause errors in the code.
24
Operators See later Having created a variable or a constant, you are going to want to give it a value by assignment, calculation or comparison. JavaScript has defined a number of operators of various types:
25
Operators Operator Explanation Arithmetic
Performs arithmetic calculations on two operands which can be variables, numbers or a number and a variable Assignment Replace a value with another Bitwise Logical consequences turn specific bits in an integer on or off Comparison Compare two values and return TRUE or FALSE Logical Logical consequences Other
26
Statements and Expressions
A statement is a line of code that is complete and correct in its syntax and performs a task. Typically, a statement ends with a semi-colon Often a single line of code ending with a semicolon Can have many statement on a single line Can have a statement spread over many lines Statements contain one or more expressions Expressions are anything that has a value! Values are anything that can be assigned to a variable!
27
Functions A function is a piece of script that does something and can be repeatedly called from a larger script Global functions already exist User-defined functions you need to write Some functions require you to pass them values or arguments Other functions simply return a value
28
Global Functions These are predefined functions that are not object-specific JavaScript does not have a large library of global functions JavaScript has a large library of methods which are functions related to objects Global functions include: escape(); eval(); isFinite(); isNAN(); parseFloat(); parseInt(); unescape()
29
User-Defined Functions
Allows you to repeatedly use the same code Allows economical use of code – don’t have to copy to different parts of the page Easy editing Simply create a function containing the code you want to repeat – and call that function from everywhere you want to use it Putting function in the header means that it won’t be run until it is called User-defined functions can also have one or more arguments that are passed to them ,and may return a value after they are executed
30
Objects Objects are the visual elements of a web page – windows, buttons, check boxes and dates Can also be more abstract elements such as math calculations and arrays There are many predefined objects You can create your own custom objects as well
31
Predefined Objects Identified by a keyword name – for example, window
You can have several instances of an object in a web page – each identified by a unique name Each object can have properties (characteristics) Each object can have methods (the things it can do) – for example, alert (), write() Each object can have events (which effect it) – for example, mouse click The relationship of an object to its constituents is shown by the use of the dot syntax
32
Properties Objects have properties that allow you to describe them – distinguishing different occurrences of the same object from one another For example you can modify a window by outer height and width, or inner display area Some objects have only one property - for example, the string object has only one property – length. Properties are applied to an object using the dot statement syntax: objectname.propertyname = “value”
33
Methods Methods are actions that objects can perform
They can be considered predefined functions for objects For example, to return the square root of three, use: math.sqrt(3); Another example: window.alert(“Hello World”);
34
Event Handlers Event handlers allow you to take advantage of events (or triggers) performed by the user – for example, mouse click or page load The event handler recognises the event taking place and then performs one or more tasks – adding interactivity to the web page Common event handlers are shown in the next slide:
35
Event Handlers Event Handler Event Trigger onAbort
An image’s loading is interrupted onBlur Focus is removed from an element onChange Contents of a form are changed onClick An element is single-clicked onDblClick An element is double-clicked onDragDrop An object is dragged-and-dropped into a window onError An error occurs when loading a web page or picture onFocus The user places the focus on an element onKeyDown The user presses a defined key onKeyPress The user presses and holds down a defined key onKeyUp The user releases a defined pressed key onLoad A web page completes loading in a browser
36
Event Handlers Event Handler Event Trigger onMouseDown
The user presses a mouse button onMouseMove The user moves the mouse pointer onMouseOut The user moves the mouse pointer from a link onMouseOver The user moves the mouse pointer to a link onMouseUp The user releases a mouse buton onMove A window or frame is moved onOpen A web page opens in a browser onReset A form is reset onResize A window or frame is resized onSelect A field in a form is selected onSubmit A user submits a form onUnload A user opens another web page
37
Control Structures Simple scripts are executed from the first statement to the last statement without interruption Often you will want the script to go one way or another – or re-execute a particular piece of code This is the purpose of control structures: if/else while do-while for switch
38
The logical flow of an if statement
39
The logical flow of an if-else statement
40
The logical flow of a while loop
41
The logical flow of a do-while loop
42
The logical flow of a for loop
43
Where do you put your JavaScript?
<html> <head> <title>A Web Page Title</title> <script type = "text/javascript"> // JavaScript goes here </script> </head> <body> // JavaScript can go here too </body> </html>
44
Where do you put your JavaScript?
<html> <head> <title>A Web Page Title</title> <script type = "text/javascript“ src = “myjavascript.js”> // JavaScript in external file </script> </head> <body> <script type = "text/javascript"> // JavaScript can go here too </body> </html>
45
JavaScript in <body> tag is executed as it is encountered…
<head> <title>A Web Page Title</title> <script type = "text/javascript"> // JavaScript Goes Here </script> </head> <body> document.write("hello"); document.write(" world"); </body> </html>
46
Writing text to page <html> <body>
<script type="text/javascript"> document.write("Hello World!"); </script> </body> </html>
47
Adding comments to handle older browsers
<html> <body> <script type="text/javascript"> <!-- document.write("Hello World!"); //--> </script> </body> </html>
48
Writing HTML tags on a page using JavaScript
<body> <script type="text/javascript"> document.write("<h1>This is a header</h1>"); </script> </body> </html>
49
First Web Project <html> <head>
<title>My First Page</title> <script type = "text/javascript"> function yetAnotherAlert(textToAlert) { alert(textToAlert); } yetAnotherAlert("This is my first JavaScript!"); </script> </head> <body> </body> </html>
50
First Web Project <html> <head>
<title>My First Page</title> <script type = "text/javascript"> function yetAnotherAlert(textToAlert) { alert(textToAlert); } yetAnotherAlert("This is my first JavaScript!"); </script> </head> <body> yetAnotherAlert("This function has been called from the body of the page!"); </body> </html>
51
First Web Project <html> <head>
<title>My First Page</title> <script type = "text/javascript“ src = “myscript.js”> </script> </head> <body> <script type = "text/javascript"> yetAnotherAlert("This function has been called from the body of the page!"); </script> </body> </html>
52
First Web Project – What have we learned?
JavaScript code consists of lines (or statements) Use the HTML <script> to embed code in HTML page <script type = "text/javascript“> Every line (statement) ends with ; (semi-colon) Code on HTML page is read/interpreted line by line from the top of the page
53
First Web Project – What have we learned?
Can be embedded using the <script> tag in either the <head> <body> An external JavaScript file can also be linked to a web page (.js extension). <script type = "text/javascript“ src = “myscript.js”> Don’t use the HTML <script> tag in the external .js file
54
First Web Project – What have we learned?
Statements can be grouped together as functions – which are created and named by the developer function yetAnotherAlert(textToAlert) { alert(textToAlert); } JavaScript is case-sensitive Keywords – for example, function – are in lowercase Indentation is used to help readability!
55
First Web Project – What have we learned?
Use curly braces { } to group statements into blocks Code in functions is only run when functions are ‘called’ Functions can be called from the <head> or (more usually) the <body> yetAnotherAlert("This is my first JavaScript!"); yetAnotherAlert("This function has been called from the body of the page!");
56
First Web Project – What have we learned?
The function name is always followed by () Arguments (or parameters) can be passed into a function: function yetAnotherAlert(textToAlert) { alert(textToAlert); } yetAnotherAlert("This is my first JavaScript!"); Note the use of " " around literal strings.
57
First Web Project – What have we learned?
There are also pre-defined functions (or methods): alert(“My name is Sue”); or alert(textToAlert); window.alert(“My name is Sue”) window.alert(textToAlert);
58
Quick question!! What is the purpose of using functions?
59
Variables Variables are containers for storing values (literals)
Can be used and re-used Rules for naming Begin with [a…z], [A…Z], or ‘_’ All subsequent characters [a…z], [A…Z], [1…9] or ‘_’ Variables are case sensitive Should not use JavaScript keywords or reserved words
60
Good or Bad Variables? var bedfordvar1 = “Bedford1";
var var = “Bedford7";
61
JavaScript is ‘weakly typed’
You do not have to declare a datatype You do not even have to declare the variable before use However, it is good practice to declare variable first Arrays are indexes of similar items. Items must have the same datatype. Powerful when used with loops.
62
Datatypes Datatypes: Null Integer (Decimal, Hexadecimal, Octal)
Float (Decimal integer, decimal point, numbers to right of decimal point, and possibly, exponent) Boolean (datatype with two states only) String – collection of characters – surrounded by double or single quotes
63
Declaring a Variable var myVariable; myVariable = "some value"; or var myVariable = "some value";
64
<script language="JavaScript"> var myVariable = "Hello";
<head> <script language="JavaScript"> var myVariable = "Hello"; </script> </head> <body> We created a variable in the header. <script language = “JavaScript”> document.write(“The variable contains: “ + myVariable); </body> Outputting a variable
65
Changing the value in a variable
<html> <head> </head> <body> <script type="text/javascript"> var firstname; firstname="Fred"; document.write(firstname); document.write("<br />"); firstname="Tom"; </script> <p>The script above declares a variable, assigns a value to it, displays the value, changes the value, and displays the value again.</p> </body> </html> Changing the value in a variable
66
What is a String? Any sequence of characters – and can contain numbers, letters or other symbols Surrounded by double or single quotes Valid: "Hello there" 'My Phone number is ‘ Non-valid: "Hello' What is your name?
67
Concatenating Strings
Combines two text strings into one longer text string: var myVariable = "ab" + "cd"; or var thisVar = “cd”; var myVariable = "ab" + thisVar;
68
Concatenating strings
<body> <script language="JavaScript"> <!— var myVariable = "Hello"; var anotherVariable = "there" var finalResults = myVariable + " " + anotherVariable; document.write(finalResults); // --> </script> </body> Concatenating strings
69
Three ways of outputting strings
<body> <script language="JavaScript"> <!-- var myGreeting = “Hello”; document.write(myGreeting); document.write(“<br />My Name is Sue”); window.alert(myGreeting + “\nMy Name is Sue”); // --> </script> </body> Three ways of outputting strings
70
String Character Codes
\ is the escape operator \” will literally place a quotation mark in a string \n is the new line character
71
Performing Calculations
Addition: For instance, Subtraction: For instance, 20 – 10 Multiplication: For instance, 10 * 20 Division: For instance, 20 / 10 Can use complex expressions: 100 / 5 – 10 100 / (5 – 10) var myVariable = 100 / 5; var myVariable = 100 / thisVar;
72
<body> <script language="JavaScript"> <!— var myVariable = 100; var anotherVariable = 200 var finalResults = myVariable + anotherVariable; document.write(finalResults); // --> </script> </body>
73
Operators The assignment operator = is used to assign values to JavaScript variables. The arithmetic operator + is used to add values together. y=5; z=2; x=y+z; What value does x contain?
74
Arithmetic Operators Given that y=5, the table below explains the arithmetic operators: Operator Description Example Result + Addition x=y+2 - Subtraction x=y-2 * Multiplication x=y*2 / Division x=y/2 % Modulus (division remainder) x=y%2 ++ Increment x=++y -- Decrement x=--y
75
Arithmetic Operators Given that y=5, the table below explains the arithmetic operators: Operator Description Example Result + Addition x=y+2 x=7 - Subtraction x=y-2 x=3 * Multiplication x=y*2 x=10 / Division x=y/2 x=2.5 % Modulus (division remainder) x=y%2 x=1 ++ Increment x=++y x=6 -- Decrement x=--y x=4
76
Assignment Operators Given that x=10 and y=5, the table below explains the assignment operators: Operator Example Same As Result = x=y += x+=y x=x+y -= x-=y x=x-y *= x*=y x=x*y /= x/=y x=x/y %= x%=y x=x%y
77
Assignment Operators Given that x=10 and y=5, the table below explains the assignment operators: Operator Example Same As Result = x=y x=5 += x+=y x=x+y x=15 -= x-=y x=x-y *= x*=y x=x*y x=50 /= x/=y x=x/y x=2 %= x%=y x=x%y x=0
78
What is the output? txt1="What a very"; txt2="nice day";
txt3=txt1+" "+txt2;
79
Adding Strings and Numbers
<body> <script type="text/javascript"> x=5+5; document.write(x); document.write("<br />"); x="5"+"5"; x=5+"5"; x="5"+5; </script> <p>The common rule is: If you add a number and a string, the result will be a string.</p> </body>
80
Comparison and Logical Operators
Comparison and logical operators are used to test for true or false. Comparison operators are used in logical statements to determine equality or difference between variables or values. Logical operators are used in determine the logic between variables or values.
81
Comparison Operators Given that x=5, the table below explains the comparison operators: Operator Description Example == is equal to x==8 is false === is exactly equal to (value and type) x===5 is true x==="5" is false != is not equal x!=8 is true > is greater than x>8 is false < is less than x<8 is true >= is greater than or equal to x>=8 is false <= is less than or equal to x<=8 is true
82
How Comparison Operators can be used:
Comparison operators can be used in conditional statements to compare values and take action depending on the result: if (age<18) document.write("Too young");
83
Logical Operators Given that x=6 and y=3, the table below explains the logical operators: Operator Description Example && and (x < 10 && y > 1) is true || or (x==5 || y==5) is false ! not !(x==y) is true
84
Conditional Operator JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. The syntax is: variablename=(condition)?value1:value2 greeting=(visitor=="PM")?"Dear Prime Minister ":"Dear"; If the variable visitor has the value of "PM", then the variable greeting will be assigned the value "Dear Prime Minister " else it will be assigned "Dear".
85
JavaScript Security Issues
reading/writing client files, opening/closing user windows, reading information from other browser windows The Sand Box – JavaScript’s Security Model Signed Scripts Same-Origin Security Policy Cross-Site Scripting (XSS) SQL Injection
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.