javascript
TRANSCRIPT
![Page 1: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/1.jpg)
INFSCI 1052
![Page 2: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/2.jpg)
Client Side versus Server Side Server side
• PHP, ASP, Cold Fusion, Ruby on Rails• Good for accessing databases
Client Side• Good for immediacy of action• Forms• WebPages• Also, Flash, Ajax
![Page 3: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/3.jpg)
Compiled versus interpreted languages• C, C#, JAVA, • JS, PHP, Python
Adding JS to a webpage• Usually add to the <head> section• Can be added to the <body> section too• Can be linked to an external JS file
![Page 4: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/4.jpg)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html;
charset=utf-8" /> <title>Untitled Document</title> </head> <script type="text/javascript"> alert('helloworld'); </script> <body> </body> </html>
![Page 5: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/5.jpg)
External Linking to JS File- Two separate lines
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head> <meta http-equiv="Content-Type" content="text/html;
charset=utf-8" /> <title>Untitled Document</title>
<script type="text/javascript" src="myprogram.js"> </script>
<script type="text/javascript"> alert('helloworld'); </script> </head>
<body> </body> </html>
![Page 6: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/6.jpg)
Linking and paths• Absolute paths
http://www.sis.pitt.edu
• Root-relative paths Using a webserver Relative to the site’s top level folder
Ex. /myfolder/index.html
• Document-relative paths Specifies path from Web page to the JS file
Ex: ../myscripts/myjsfile.js
![Page 7: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/7.jpg)
JavaScript:The Missing Manual http://www.sawmac.com/js/tutorials/e
xamples/index.html Completed tutorials section and
working tutorials Focus is on basic JS and using JS
libraries such as JQuery.
![Page 8: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/8.jpg)
Writing text to a web page• Document.write (‘<p> Hello World </P’);• 1.2.html
Attaching external file• 1.3.html
![Page 9: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/9.jpg)
Errors and debugging• If error in code typically nothing happens
Web Browsers have consoles that can display JS errors
Firefox has better console than IE• Lists type of error, name of file, and line number• Select Tools->Error Console
Common Errors• Missing semicolon, missing quote mark, misspelled
word, missing ), unterminated string literal, missing }
![Page 10: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/10.jpg)
Statement: the basic unit of JS program, ends in semicolon
Data Types• Number
Integer or fractional• String
Use quote marks• Boolean
True or False
Variables• Var varname;
Begin with letter, $, or __ Can only contain letters, numbers, $ and __ CaSE SENSITIVE
![Page 11: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/11.jpg)
Var Examples• var number=0;• var name=‘Bob’;• var age=26;• var open=true;
Math operators and order of operations apply• +, -, *, / • Use parenthesis to ensure correct order of
operations
![Page 12: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/12.jpg)
Addition and concatenation• + sign for both purposes• When adding two numbers the + sign does
addition• When “adding” two string or a number and a
string then the concatenation function is performed Ex. var fname = ‘Bill’; var lname = ‘Smith’; var totalname=fname+lname;
Sample: 2.1.html
![Page 13: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/13.jpg)
Arrays• var months = [‘Jan’, ‘Feb’, ‘Mar’];• var months = new Array(‘Jan’, ‘Feb’, ‘Mar’];• Empty array
var months =[];• Accessing arrays
nameofarray[#]; Zero based so nameofarray[2] references the third
element• Adding element to end of array
Nameofarray[nameofarray.length] = ‘text’; Var colors = [‘red’, ‘blue’, green’]
Colors = [colors.length]=‘purple’;
![Page 14: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/14.jpg)
Arrays• Push command to add multiple elements to the array
colors.push(‘pink’, orange’, ‘brown’);• Add to the beginning of an array
.unshift• Push and unshift return a value: the number of items in
the array• Removing items in an array
pop() – removes the last item shift() – removes the first item Ex. var x = [0,1,2,3]; var removeditem = x.pop()
• Adding and deleting in middle of array splice function
• Sample: 2.3.html
![Page 15: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/15.jpg)
Logic
If (condition) {Code statements}
• Comparison operators• >, <, >=, <=
• If else and if else if• && = and • || = or• ! = not• Sample: 3.1.html
![Page 16: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/16.jpg)
Loops• While
while (condition) {JS statements
}
• For Loopsfor (var=x, x<=100; x++) {
JS statements}
Do While Loopsdo {
JS statements} while (condition);
• Sample: dowhile loop
![Page 17: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/17.jpg)
FunctionsFunction functionName() {
JS Statements}
Sample: 3.2.html Send information to functions via
arguments and paramaters
![Page 18: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/18.jpg)
function functionName ( paramater 1, paramater2) {JS Statements};
functionName (argument1, argument2);
• Retrieving Information from functions• Function functionName (paramater1, paramater2) {• JS statements• Return value; • }
• Sample: 3.3.html
![Page 19: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/19.jpg)
DOM• Document Object Model• Working with Web pages
Identify an element on a page Do something with the element
Add/remove a class attribute Change a property of the element Add new content Remove the element Extract information from the element
![Page 20: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/20.jpg)
Provides the information that JS needs to interact with elements on the webpage
A navigation structure or map of the elements on the webpage
Standard from the W3C• Most browsers have adopted but in different
ways Hierarchical structure of the tags in a
web page
![Page 21: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/21.jpg)
Tags• Parents• Chidren• Siblings• All nodes• Text is nodes too• Nesting determines the relationships
Selecting a page element• getElementById()
Locating a single element that has a unique ID document.getElementById(‘header’)
Searches page for a tag with an ID of ‘header’ Typically the results of this action are stored in a variable
var headNode=document.getElementById(‘header’);
![Page 22: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/22.jpg)
GetElementsByTagName• document.getElementsByTagName (‘a’);
Usually stored in a var var myLinks=document.getElementsByTagName
(‘a’); Find all <a> tags and store results in a var named
myLinks This action returns a list of nodes instead of a single
node Similar to arrays
Can access a single node using index notation Can use the length property Can loop using a for loop
![Page 23: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/23.jpg)
Accessing near by nodes• .childNodes
A property of a node Ex.
var headline = document.getElementById(‘header’);var headlineChildren = headline.childNodes;
• .parentNode• A property that represents the direct parent of a node
• .nextSibling and .previousSibling• Properties that access next and previous siblings
• .innerHTML Not a standard part of DOM but most browsers implement it Accesses the text part of a node
![Page 24: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/24.jpg)
Examplevar pTags = document.getElementsByTagName(‘p’);
var theP = pTags[0]; alert(theP.innerHTML);
Opens an alert box and prints out the text of the first paragraph.
![Page 25: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/25.jpg)
JavaScript Quiz• quiz.html
JavaScript Libraries• Small file size• Web oriented• Tested• Free• Large developer community
![Page 26: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/26.jpg)
Jquery.js is a single file that you download that you link to a Web page• http://docs.jquery.com/Downloading_jQuery
Uncompressed – includes comments Minified – compression
Browser downloads the file once and caches it After downloading the file place the library file in
your project Link this file to your web page
<script type=“text/javascript” src=“js/jquery.js”></script>
Once linked write your javascript program
![Page 27: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/27.jpg)
Example:• <script type=“text/javascript”
src=“js/jquery.js”></script>
• <script type=“text/javascript”> Javascript code here
• </script>
• Note: here we created a folder called js and put the downloaded jquery.js file in it.
![Page 28: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/28.jpg)
Selecting page elements• CSS Selectors
Use the jQuery object to select elements $(‘css-selector’) Can use all CSS 2.1 selectors Ex: $(‘#header’) Typically used to select ID’s, classes and element
selectors
![Page 29: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/29.jpg)
ID Selector• <p id=“key”>The key point </p>• var keyparagraph=document.getElementById
(‘key’);• Or• var keyparagraph=$(‘#key’);• Timesaver
Element Selector• var mylist=$(‘a’);
Class selector• var mystuff= $(‘.classthings’)
Selects all elements with same class name
![Page 30: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/30.jpg)
Advanced selectors• Descendent selectors
$(‘#header a’)• Child selectors
$(‘body > p’)• Adjacent siblings• Attribute selectors
More advanced selectors not supported by all browsers just as in CSS
![Page 31: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/31.jpg)
Jquery Selections• Not like the DOM based results• Can’t use traditional DOM methods on them
Ex innerHTML will not work• Most DOM based actions have JQuery
equivalent Automatic Looping
• Jquery functions have looping built-in $(‘#slideshow img’).hide();
Automatically slects all images inside of div tag with ID slideshow and hides images
![Page 32: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/32.jpg)
Chaining• Ability to perform several operations on a
selection of elements• Ex:
$(‘#popUp’).width(300).height(300).text(‘Message’).fadeIn(1000); Sets width and height and adds text and fades inside
div with ID popUp Chaining with the period
![Page 33: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/33.jpg)
Some functions• .html
Works like innerHtml Read current element ( can retrieve what is in an
element) Replace info in current element $(‘#header’).html(‘<p> Look at me I’m a new
header</p>);
• .remove Replace or remove an element $(‘#footer’).remove;
![Page 34: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/34.jpg)
What else can Jquery do?• Select elements• Change value of elements• Replace elements• Remove elements• Change value of elements attribute• Add a class to a tag• Change a CSS property• Get the value of an attribute
![Page 35: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/35.jpg)
Functions• .addClass and .removeClass
Adds a specified class to an element Of course the newly added CSS class must have been
written .removeClass removes a class
• .css Change CSS property
$(‘body’).css(‘padding’,50); .attr
Read/Set an element attribute var attributeinfo=$(‘banner img’).attr(‘src’); Reads and stores the src attribute of the image in the
banner A second argument would set the src
![Page 36: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/36.jpg)
Example• Using .each• this• .clone• .addClass• .removeClass• .before
pullquote
![Page 37: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/37.jpg)
Events$(document).ready(function() {
Code here
});• Makes sure the html of the page loads before
the Javascript runs.• Two step process
• 1) Identify the page element you wish to respond to
• 2) Assign an event and define a function to run when event occurs
![Page 38: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/38.jpg)
Events• Mouse Events
click dblclick mousedown mouseup mouseover mouseout
• Document Window Events Load Resize Scroll Unload
• Form Events Submit Reset - button Change Focus – enter a field Blur – exit a field
![Page 39: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/39.jpg)
Events• Keyboard Events
keypress keydown Keyup
Using Events with Jquery• 1) Select element• 2) Assign an event
$(‘a’).mouseover(); - adds mousever to every link • 3) Pass a function to event
$(‘a’).mouseover(startSomething()); Or pass an anonymous function$(‘a’).mouseover (function() {Code here});
![Page 40: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/40.jpg)
Example:• desecendent selectors• .mouseover• anonymous function• .addClass• .mouseout
Example:• Table.html
![Page 41: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/41.jpg)
Events• When web browser fires an event information is
stored about the event in an event object Vertical and horizontal coordinates the element when event occurred The event object is available to the function handling
the event• Ex
$(document).click(function(evt){ var xPos=evt.pageX; var yPos=evt.pageY; });
Note: evt is not a keyword – use any word
![Page 42: JavaScript](https://reader033.vdocument.in/reader033/viewer/2022060108/554f6412b4c905bb178b493a/html5/thumbnails/42.jpg)
Stopping an event’s normal behavior• Evt. preventDefault();• Ex. To prevent a link being clicked and
moving off the page