SlideShare a Scribd company logo
The JavaScript Language
1
CP 221: Internet programming and
applications I
(CIVE)
Objectives
• Learn about JavaScript
• Using JavaScript in HTML
• Language Elements
• Variables
• Operators
• Control Statements
• Functions
• Objects
• Exception handling.
2
About JavaScript
• JavaScript was designed to add interactivity to HTML
pages
• JavaScript is a scripting language (a scripting language is
a lightweight programming language)
• A JavaScript consists of lines of executable computer
code
• JavaScript is an interpreted language (means that scripts
execute without preliminary compilation)
• Everyone can use JavaScript without purchasing a license
3
When not to use JavaScript
• When you need to access other resources.
– Files
– Programs
– Databases
• When you are using sensitive or copyrighted data or
algorithms.
– Your JavaScript code is open to the public.
4
Dealing with old browsers
• Some old browsers do not recognize script tags
• These browsers will ignore the script tags but will display the
included JavaScript
• To get old browsers to ignore the whole thing, use:
<script type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
• The <!-- introduces an HTML comment
• To get JavaScript to ignore the HTML close comment, -->, the //
starts a JavaScript comment, which extends to the end of the line
5
Objects in JavaScript
• Objects have attributes and methods.
• Many pre-defined objects and object types.
• Using objects follows the syntax of C++/Java:
objectname.attributename
objectname.methodname()
• JavaScript is not Object Oriented – but Object-
Based
6
Three ways to create an object
• You can use an object literal:
– var course = { number: "CIT597", teacher="Dr. Dave" }
• You can use new to create a “blank” object, and add fields
to it later:
– var course = new Object();
course.number = "CIT597";
course.teacher = "Dr. Dave";
• You can write and use a constructor:
– function Course(n, t) { // best placed in <head>
this.number = n;
this.teacher = t;
}
– var course = new Course("CIT597", "Dr. Dave"); 7
The document object
• Many attributes of the current document are available via the
document object:
Title Referrer
URL Images
Forms Links
Colors
8
document Methods
• document.write() like a print statement – the output
goes into the HTML document.
• document.writeln() adds a newline after printing.
• document.getElementById() Returns the element that
has the ID attribute with the specified value
document.write("My title is " +
document.title);
9
Example
<HEAD>
<TITLE>JavaScript is Javalicious</TITLE>
</HEAD>
<BODY>
<h3>I am a web page and here is my
name:</h3>
<script type=”text/Javascript”>
document.write(document.title);
</script>
<hr>
10
The navigator Object
• Represents the browser. Read-only!
• Attributes include:
appName
appVersion
platform
11
navigator Example
if (navigator.appName ==
"Microsoft Internet Explorer") {
document.writeln("<H1>This page
requires Netscape!</H1>");
}
12
The window Object
• Represents the current window.
• There are possible many objects of type Window, the
predefined object window represents the current window.
• Access to, and control of, a number of properties including
position and size.
13
window attributes
• document
• name
• status the status line
• parent
14
some window methods
alert()
close()
prompt()
moveTo() moveBy()
open()
scroll() scrollTo()
resizeBy()resizeTo()
15
The Math Object
• Access to mathematical functions and constants.
• Constants: Math.PI
• Methods:
Math.abs(), Math.sin(), Math.log(), Math.max(),
Math.pow(), Math.random(), Math.sqrt(), …
16
Math object in use
// returns an integer between 1 and 6
function roll() {
var x = Math.random();
// convert to range [0,6.0)
x = x * 6;
// add 1 and convert to int
return parseInt(1+x );
}
document.writeln("Roll is “ + roll() ); 17
Math object in use
<script type ="text/javascript">
<!--
var input1 = window.prompt("Enter first number", "0");
var input2 = window.prompt("Enter second number", "0");
var input3 = window.prompt("Enter third number", "0");
var value1 = parseFloat(input1);
var value2 = parseFloat(input2);
var value3 = parseFloat(input3);
var maxValue = maximum( value1, value2, value3);
document.writeln("First number: " + value1 +
"<br /> Second number: " + value2 +
"<br />Third number: " + value3 +
"<br />Maximum is: " +maxValue );
function maximum(x,y,z)
{
return Math.max(x,Math.max(y,z));
}
//-->
</script>
18
Array Objects
• Arrays are supported as objects.
• Attribute length
• Methods include:
concat join pop push reverse sort
19
Some similarity to C++
• Array indexes start at 0.
• Syntax for accessing an element is the same:
a[3]++;
blah[i] = i*72;
20
New Stuff (different from
C++)
• Arrays can grow dynamically – just add new elements at the
end.
• Arrays can have holes, elements that have no value.
• Array elements can be anything
• numbers, strings, or arrays!
21
Four ways to create an array
• You can use an array literal:
var colors = ["red", "green", "blue"];
• You can use new Array() to create an empty array:
– var colors = new Array();
• You can add elements to the array later:
colors[0] = "red"; colors[2] = "blue"; colors[1]="green";
• You can use new Array(n) with a single numeric
argument to create an array of that size
– var colors = new Array(3);
• You can use new Array(…) with two or more arguments
to create an array containing those values:
– var colors = new Array("red","green", "blue");
22
The length of an array
• If myArray is an array, its length is given by
myArray.length
• Array length can be changed by assignment beyond the
current length
• Example: var myArray = new Array(5); myArray[10] = 3;
• Arrays are sparse, that is, space is only allocated for
elements that have been assigned a value
• Example: myArray[50000] = 3; is perfectly OK
• But indices must be between 0 and 232-1
• As in C and Java, there are no two-dimensional arrays; but
you can have an array of arrays: board[3][3]
23
Arrays examples
• car = { myCar: "Saturn", 7: "Mazda" }
– car[7] is the same as car.7
– car.myCar is the same as car["myCar"]
• If you know the name of a property, you can use dot notation:
car.myCar
• If you don’t know the name of a property, but you have it in a
variable (or can compute it), you must use array notation:
car["my" + "Car"]
• var colors = [" blue ",
" green ",
" yellow "];
var x = window.prompt("enter a number ");
document.body.style.background = colors[x];
24
Array of Arrays Example
var board = [ [1,2,3],
[4,5,6],
[7,8,9] ];
for (i=0;i<3;i++)
for (j=0;j<3;j++)
board[i][j]++;
25
Array functions
• If myArray is an array,
– myArray.sort() sorts the array alphabetically
– myArray.sort(function(a, b) { return a - b; }) sorts numerically
– myArray.reverse() reverses the array elements
– myArray.push(…) adds any number of new elements to the end of
the array, and increases the array’s length
– myArray.pop() removes and returns the last element of the array,
and decrements the array’s length
– myArray.toString() returns a string containing the values of the
array elements, separated by commas
26
Passing Arrays to Functions
• To pass an array argument to a function, specify the name of
the array without brackets.
var a = [1,2,3,4,5];
outputArray(" Your array: ", a);
function outputArray(heading, theArray)
{
document.writeln(heading + theArray.join("
") + " <br /> ");
} 27
JavaScript HTML DOM
• With the HTML DOM, JavaScript can access and
change all the elements of an HTML document.
• The HTML DOM (Document Object Model)
• When a web page is loaded, the browser creates
a Document Object Model of the page.
• The HTML DOM model is constructed as a tree
of Objects:
12/3
The HTML DOM Tree of
Objects
12/3
The HTML DOM Tree of
Objects
12/3
• With the object model, JavaScript gets all the power it needs
to create dynamic HTML:
• JavaScript can change all the HTML elements in the page
• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the page
• JavaScript can create new HTML events in the page
What is the DOM?
• The DOM is a W3C (World Wide Web
Consortium) standard.
• The DOM defines a standard for accessing
documents:
• "The W3C Document Object Model (DOM) is a
platform and language-neutral interface that
allows programs and scripts to dynamically
access and update the content, structure, and
style of a document."
12/3
What is the DOM?
The W3C DOM standard is separated into 3
different parts:
• Core DOM - standard model for all document
types
• XML DOM - standard model for XML documents
• HTML DOM - standard model for HTML
documents
12/3
What is the HTML DOM?
• The HTML DOM is a standard object model and
programming interface for HTML. It defines:
 The HTML elements as objects
 The properties of all HTML elements
 The methods to access all HTML elements
 The events for all HTML elements
• In other words: The HTML DOM is a standard for
how to get, change, add, or delete HTML
elements.
12/3
JavaScript - HTML DOM
Methods
• HTML DOM methods are actions you can perform (on HTML
Elements).
• HTML DOM properties are values (of HTML Elements) that
you can set or change.
• The HTML DOM can be accessed with JavaScript (and with
other programming languages).
• In the DOM, all HTML elements are defined as objects.
• The programming interface is the properties and methods of
each object.
• A property is a value that you can get or set (like changing the
content of an HTML element).
• A method is an action you can do (like add or deleting an
HTML element).
12/3
Example
The following example changes the content (the
innerHTML) of the <p> element with id="demo":
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"Hello World!";
</script>
</body>
</html>
12/3
Example..
• In the example above, getElementById is a method, while
innerHTML is a property.
12/3
The getElementById Method
• The most common way to access an HTML
element is to use the id of the element.
• In the example above the getElementById
method used id="demo" to find the element. 12/3
The innerHTML Property
• The easiest way to get the content of an element
is by using the innerHTML property.
• The innerHTML property is useful for getting or
replacing the content of HTML elements.
• The innerHTML property can be used to get or
change any HTML element, including <html> and
<body>
12/3
The HTML DOM Document
Object
• The document object represents your web page.
• If you want to access any element in an HTML
page, you always start with accessing the
document object.
• Below are some examples of how you can use
the document object to access and manipulate
HTML.
12/3
The HTML DOM Document
Object
 Finding HTML Elements
12/3
Changing HTML Elements
12/3
JavaScript HTML DOM
Elements
How to find and access HTML
elements in an HTML page?
12/3
JavaScript HTML DOM
Elements
 Finding HTML Elements
• Often, with JavaScript, you want to manipulate HTML
elements.
• To do so, you have to find the elements first. There are several
ways to do this:
 Finding HTML elements by id
 Finding HTML elements by tag name
 Finding HTML elements by class name
 Finding HTML elements by CSS selectors
 Finding HTML elements by HTML object collections
12/3
JavaScript HTML DOM
Elements
 Finding HTML Element by Id
 The easiest way to find an HTML element in the DOM, is by
using the element id.
 This example finds the element with id="intro":
12/3
JavaScript HTML DOM
Elements
!DOCTYPE html>
<html>
<body>
<h2>Finding HTML Elements by Id</h2>
<p id="intro">Hello World!</p>
<p>This example demonstrates the <b>getElementsById</b>
method.</p>
<p id="demo"></p>
<script>
var myElement = document.getElementById("intro");
document.getElementById("demo").innerHTML =
"The text from the intro paragraph is " + myElement.innerHTML;
</script>
12/3
JavaScript HTML DOM
Elements
 If the element is found, the method will return the
element as an object (in myElement).
 If the element is not found, myElement will contain null.
12/3
JavaScript HTML DOM Elements(Finding HTML
Elements by Tag Name)
<!DOCTYPE html>
<html>
<body>
<h2>Finding HTML Elements by Tag Name</h2>
<p>Hello World!</p>
<p>This example demonstrates the <b>getElementsByTagName</b>
method.</p>
<p id="demo"></p>
<script>
var x = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML =
'The text in first paragraph (index 0) is: ' + x[0].innerHTML;
</script>
12/3
Changing HTML Content
• The easiest way to modify the content of an
HTML element is by using the innerHTML
property.
• To change the content of an HTML element, use
this syntax:
document.getElementById(id).innerHTML = new
HTML
• This example changes the content of a <p>
element:
12/3
Changing HTML Content
<html>
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML =
"New text!";
</script>
</body>
</html>
12/3
Changing the Value of an
Attribute
• To change the value of an HTML attribute, use this
syntax:
document.getElementById(id).attribute = new value
• This example changes the value of the src attribute of an
<img> element: 12/3
Changing the Value of an
Attribute
<!DOCTYPE html>
<html>
<body>
<img id="myImage" src="smiley.gif">
<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>
</body>
</html>
12/3
Changing HTML Style
• To change the style of an HTML element, use this
syntax:
document.getElementById(id).style.property =
new style
• The following example changes the style of a <p>
element:
12/3
Changing HTML Style
• <html>
<body>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color = "blue";
</script>
<p>The paragraph above was changed by a script.</p>
</body>
</html>
12/3
Using Events
• The HTML DOM allows you to execute code when an event
occurs.
• Events are generated by the browser when "things happen" to
HTML elements:
 An element is clicked on
 The page has loaded
 Input fields are changed
• This example changes the style of the HTML element with
id="id1", when the user clicks a button:
12/3
Using Events
<!DOCTYPE html>
<html>
<body>
<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
</body>
</html>
12/3
The End
56

More Related Content

Similar to lecture 6 javascript event and event handling.ppt (20)

Java script
Java scriptJava script
Java script
Adrian Caetano
 
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPTHSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
AAFREEN SHAIKH
 
Java script
Java scriptJava script
Java script
vishal choudhary
 
Week3
Week3Week3
Week3
Will Gaybrick
 
Javascript.ppt
Javascript.pptJavascript.ppt
Javascript.ppt
NoralieNicol
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
Manvendra Singh
 
JavaScripts & jQuery
JavaScripts & jQueryJavaScripts & jQuery
JavaScripts & jQuery
Asanka Indrajith
 
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
sharvaridhokte
 
JavaScript Basics with baby steps
JavaScript Basics with baby stepsJavaScript Basics with baby steps
JavaScript Basics with baby steps
Muhammad khurram khan
 
gdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptxgdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptx
sandeshshahapur
 
Java script
Java scriptJava script
Java script
Yoga Raja
 
javaScript and jQuery
javaScript and jQueryjavaScript and jQuery
javaScript and jQuery
Mehrab Hossain
 
jQuery with javascript training by Technnovation Labs
jQuery with javascript training by Technnovation LabsjQuery with javascript training by Technnovation Labs
jQuery with javascript training by Technnovation Labs
Prasad Shende
 
CSC PPT 12.pptx
CSC PPT 12.pptxCSC PPT 12.pptx
CSC PPT 12.pptx
DrRavneetSingh
 
Extjs
ExtjsExtjs
Extjs
Girish Srivastava
 
Lecture 5: Client Side Programming 1
Lecture 5: Client Side Programming 1Lecture 5: Client Side Programming 1
Lecture 5: Client Side Programming 1
Artificial Intelligence Institute at UofSC
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
Bui Kiet
 
Introduction to java script, how to include java in HTML
Introduction to java script, how to include java in HTMLIntroduction to java script, how to include java in HTML
Introduction to java script, how to include java in HTML
backiyalakshmi14
 
Java Script Programming on Web Application
Java Script Programming on Web ApplicationJava Script Programming on Web Application
Java Script Programming on Web Application
SripathiRavi1
 
Introduction to JavaScript, functions, DOM
Introduction to JavaScript, functions, DOMIntroduction to JavaScript, functions, DOM
Introduction to JavaScript, functions, DOM
LikhithaBrunda
 
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPTHSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
AAFREEN SHAIKH
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
Manvendra Singh
 
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
sharvaridhokte
 
gdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptxgdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptx
sandeshshahapur
 
jQuery with javascript training by Technnovation Labs
jQuery with javascript training by Technnovation LabsjQuery with javascript training by Technnovation Labs
jQuery with javascript training by Technnovation Labs
Prasad Shende
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
Bui Kiet
 
Introduction to java script, how to include java in HTML
Introduction to java script, how to include java in HTMLIntroduction to java script, how to include java in HTML
Introduction to java script, how to include java in HTML
backiyalakshmi14
 
Java Script Programming on Web Application
Java Script Programming on Web ApplicationJava Script Programming on Web Application
Java Script Programming on Web Application
SripathiRavi1
 
Introduction to JavaScript, functions, DOM
Introduction to JavaScript, functions, DOMIntroduction to JavaScript, functions, DOM
Introduction to JavaScript, functions, DOM
LikhithaBrunda
 

Recently uploaded (20)

TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Ad

lecture 6 javascript event and event handling.ppt

  • 1. The JavaScript Language 1 CP 221: Internet programming and applications I (CIVE)
  • 2. Objectives • Learn about JavaScript • Using JavaScript in HTML • Language Elements • Variables • Operators • Control Statements • Functions • Objects • Exception handling. 2
  • 3. About JavaScript • JavaScript was designed to add interactivity to HTML pages • JavaScript is a scripting language (a scripting language is a lightweight programming language) • A JavaScript consists of lines of executable computer code • JavaScript is an interpreted language (means that scripts execute without preliminary compilation) • Everyone can use JavaScript without purchasing a license 3
  • 4. When not to use JavaScript • When you need to access other resources. – Files – Programs – Databases • When you are using sensitive or copyrighted data or algorithms. – Your JavaScript code is open to the public. 4
  • 5. Dealing with old browsers • Some old browsers do not recognize script tags • These browsers will ignore the script tags but will display the included JavaScript • To get old browsers to ignore the whole thing, use: <script type="text/javascript"> <!-- document.write("Hello World!") //--> </script> • The <!-- introduces an HTML comment • To get JavaScript to ignore the HTML close comment, -->, the // starts a JavaScript comment, which extends to the end of the line 5
  • 6. Objects in JavaScript • Objects have attributes and methods. • Many pre-defined objects and object types. • Using objects follows the syntax of C++/Java: objectname.attributename objectname.methodname() • JavaScript is not Object Oriented – but Object- Based 6
  • 7. Three ways to create an object • You can use an object literal: – var course = { number: "CIT597", teacher="Dr. Dave" } • You can use new to create a “blank” object, and add fields to it later: – var course = new Object(); course.number = "CIT597"; course.teacher = "Dr. Dave"; • You can write and use a constructor: – function Course(n, t) { // best placed in <head> this.number = n; this.teacher = t; } – var course = new Course("CIT597", "Dr. Dave"); 7
  • 8. The document object • Many attributes of the current document are available via the document object: Title Referrer URL Images Forms Links Colors 8
  • 9. document Methods • document.write() like a print statement – the output goes into the HTML document. • document.writeln() adds a newline after printing. • document.getElementById() Returns the element that has the ID attribute with the specified value document.write("My title is " + document.title); 9
  • 10. Example <HEAD> <TITLE>JavaScript is Javalicious</TITLE> </HEAD> <BODY> <h3>I am a web page and here is my name:</h3> <script type=”text/Javascript”> document.write(document.title); </script> <hr> 10
  • 11. The navigator Object • Represents the browser. Read-only! • Attributes include: appName appVersion platform 11
  • 12. navigator Example if (navigator.appName == "Microsoft Internet Explorer") { document.writeln("<H1>This page requires Netscape!</H1>"); } 12
  • 13. The window Object • Represents the current window. • There are possible many objects of type Window, the predefined object window represents the current window. • Access to, and control of, a number of properties including position and size. 13
  • 14. window attributes • document • name • status the status line • parent 14
  • 15. some window methods alert() close() prompt() moveTo() moveBy() open() scroll() scrollTo() resizeBy()resizeTo() 15
  • 16. The Math Object • Access to mathematical functions and constants. • Constants: Math.PI • Methods: Math.abs(), Math.sin(), Math.log(), Math.max(), Math.pow(), Math.random(), Math.sqrt(), … 16
  • 17. Math object in use // returns an integer between 1 and 6 function roll() { var x = Math.random(); // convert to range [0,6.0) x = x * 6; // add 1 and convert to int return parseInt(1+x ); } document.writeln("Roll is “ + roll() ); 17
  • 18. Math object in use <script type ="text/javascript"> <!-- var input1 = window.prompt("Enter first number", "0"); var input2 = window.prompt("Enter second number", "0"); var input3 = window.prompt("Enter third number", "0"); var value1 = parseFloat(input1); var value2 = parseFloat(input2); var value3 = parseFloat(input3); var maxValue = maximum( value1, value2, value3); document.writeln("First number: " + value1 + "<br /> Second number: " + value2 + "<br />Third number: " + value3 + "<br />Maximum is: " +maxValue ); function maximum(x,y,z) { return Math.max(x,Math.max(y,z)); } //--> </script> 18
  • 19. Array Objects • Arrays are supported as objects. • Attribute length • Methods include: concat join pop push reverse sort 19
  • 20. Some similarity to C++ • Array indexes start at 0. • Syntax for accessing an element is the same: a[3]++; blah[i] = i*72; 20
  • 21. New Stuff (different from C++) • Arrays can grow dynamically – just add new elements at the end. • Arrays can have holes, elements that have no value. • Array elements can be anything • numbers, strings, or arrays! 21
  • 22. Four ways to create an array • You can use an array literal: var colors = ["red", "green", "blue"]; • You can use new Array() to create an empty array: – var colors = new Array(); • You can add elements to the array later: colors[0] = "red"; colors[2] = "blue"; colors[1]="green"; • You can use new Array(n) with a single numeric argument to create an array of that size – var colors = new Array(3); • You can use new Array(…) with two or more arguments to create an array containing those values: – var colors = new Array("red","green", "blue"); 22
  • 23. The length of an array • If myArray is an array, its length is given by myArray.length • Array length can be changed by assignment beyond the current length • Example: var myArray = new Array(5); myArray[10] = 3; • Arrays are sparse, that is, space is only allocated for elements that have been assigned a value • Example: myArray[50000] = 3; is perfectly OK • But indices must be between 0 and 232-1 • As in C and Java, there are no two-dimensional arrays; but you can have an array of arrays: board[3][3] 23
  • 24. Arrays examples • car = { myCar: "Saturn", 7: "Mazda" } – car[7] is the same as car.7 – car.myCar is the same as car["myCar"] • If you know the name of a property, you can use dot notation: car.myCar • If you don’t know the name of a property, but you have it in a variable (or can compute it), you must use array notation: car["my" + "Car"] • var colors = [" blue ", " green ", " yellow "]; var x = window.prompt("enter a number "); document.body.style.background = colors[x]; 24
  • 25. Array of Arrays Example var board = [ [1,2,3], [4,5,6], [7,8,9] ]; for (i=0;i<3;i++) for (j=0;j<3;j++) board[i][j]++; 25
  • 26. Array functions • If myArray is an array, – myArray.sort() sorts the array alphabetically – myArray.sort(function(a, b) { return a - b; }) sorts numerically – myArray.reverse() reverses the array elements – myArray.push(…) adds any number of new elements to the end of the array, and increases the array’s length – myArray.pop() removes and returns the last element of the array, and decrements the array’s length – myArray.toString() returns a string containing the values of the array elements, separated by commas 26
  • 27. Passing Arrays to Functions • To pass an array argument to a function, specify the name of the array without brackets. var a = [1,2,3,4,5]; outputArray(" Your array: ", a); function outputArray(heading, theArray) { document.writeln(heading + theArray.join(" ") + " <br /> "); } 27
  • 28. JavaScript HTML DOM • With the HTML DOM, JavaScript can access and change all the elements of an HTML document. • The HTML DOM (Document Object Model) • When a web page is loaded, the browser creates a Document Object Model of the page. • The HTML DOM model is constructed as a tree of Objects: 12/3
  • 29. The HTML DOM Tree of Objects 12/3
  • 30. The HTML DOM Tree of Objects 12/3 • With the object model, JavaScript gets all the power it needs to create dynamic HTML: • JavaScript can change all the HTML elements in the page • JavaScript can change all the HTML attributes in the page • JavaScript can change all the CSS styles in the page • JavaScript can remove existing HTML elements and attributes • JavaScript can add new HTML elements and attributes • JavaScript can react to all existing HTML events in the page • JavaScript can create new HTML events in the page
  • 31. What is the DOM? • The DOM is a W3C (World Wide Web Consortium) standard. • The DOM defines a standard for accessing documents: • "The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document." 12/3
  • 32. What is the DOM? The W3C DOM standard is separated into 3 different parts: • Core DOM - standard model for all document types • XML DOM - standard model for XML documents • HTML DOM - standard model for HTML documents 12/3
  • 33. What is the HTML DOM? • The HTML DOM is a standard object model and programming interface for HTML. It defines:  The HTML elements as objects  The properties of all HTML elements  The methods to access all HTML elements  The events for all HTML elements • In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements. 12/3
  • 34. JavaScript - HTML DOM Methods • HTML DOM methods are actions you can perform (on HTML Elements). • HTML DOM properties are values (of HTML Elements) that you can set or change. • The HTML DOM can be accessed with JavaScript (and with other programming languages). • In the DOM, all HTML elements are defined as objects. • The programming interface is the properties and methods of each object. • A property is a value that you can get or set (like changing the content of an HTML element). • A method is an action you can do (like add or deleting an HTML element). 12/3
  • 35. Example The following example changes the content (the innerHTML) of the <p> element with id="demo": <html> <body> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "Hello World!"; </script> </body> </html> 12/3
  • 36. Example.. • In the example above, getElementById is a method, while innerHTML is a property. 12/3
  • 37. The getElementById Method • The most common way to access an HTML element is to use the id of the element. • In the example above the getElementById method used id="demo" to find the element. 12/3
  • 38. The innerHTML Property • The easiest way to get the content of an element is by using the innerHTML property. • The innerHTML property is useful for getting or replacing the content of HTML elements. • The innerHTML property can be used to get or change any HTML element, including <html> and <body> 12/3
  • 39. The HTML DOM Document Object • The document object represents your web page. • If you want to access any element in an HTML page, you always start with accessing the document object. • Below are some examples of how you can use the document object to access and manipulate HTML. 12/3
  • 40. The HTML DOM Document Object  Finding HTML Elements 12/3
  • 42. JavaScript HTML DOM Elements How to find and access HTML elements in an HTML page? 12/3
  • 43. JavaScript HTML DOM Elements  Finding HTML Elements • Often, with JavaScript, you want to manipulate HTML elements. • To do so, you have to find the elements first. There are several ways to do this:  Finding HTML elements by id  Finding HTML elements by tag name  Finding HTML elements by class name  Finding HTML elements by CSS selectors  Finding HTML elements by HTML object collections 12/3
  • 44. JavaScript HTML DOM Elements  Finding HTML Element by Id  The easiest way to find an HTML element in the DOM, is by using the element id.  This example finds the element with id="intro": 12/3
  • 45. JavaScript HTML DOM Elements !DOCTYPE html> <html> <body> <h2>Finding HTML Elements by Id</h2> <p id="intro">Hello World!</p> <p>This example demonstrates the <b>getElementsById</b> method.</p> <p id="demo"></p> <script> var myElement = document.getElementById("intro"); document.getElementById("demo").innerHTML = "The text from the intro paragraph is " + myElement.innerHTML; </script> 12/3
  • 46. JavaScript HTML DOM Elements  If the element is found, the method will return the element as an object (in myElement).  If the element is not found, myElement will contain null. 12/3
  • 47. JavaScript HTML DOM Elements(Finding HTML Elements by Tag Name) <!DOCTYPE html> <html> <body> <h2>Finding HTML Elements by Tag Name</h2> <p>Hello World!</p> <p>This example demonstrates the <b>getElementsByTagName</b> method.</p> <p id="demo"></p> <script> var x = document.getElementsByTagName("p"); document.getElementById("demo").innerHTML = 'The text in first paragraph (index 0) is: ' + x[0].innerHTML; </script> 12/3
  • 48. Changing HTML Content • The easiest way to modify the content of an HTML element is by using the innerHTML property. • To change the content of an HTML element, use this syntax: document.getElementById(id).innerHTML = new HTML • This example changes the content of a <p> element: 12/3
  • 49. Changing HTML Content <html> <body> <p id="p1">Hello World!</p> <script> document.getElementById("p1").innerHTML = "New text!"; </script> </body> </html> 12/3
  • 50. Changing the Value of an Attribute • To change the value of an HTML attribute, use this syntax: document.getElementById(id).attribute = new value • This example changes the value of the src attribute of an <img> element: 12/3
  • 51. Changing the Value of an Attribute <!DOCTYPE html> <html> <body> <img id="myImage" src="smiley.gif"> <script> document.getElementById("myImage").src = "landscape.jpg"; </script> </body> </html> 12/3
  • 52. Changing HTML Style • To change the style of an HTML element, use this syntax: document.getElementById(id).style.property = new style • The following example changes the style of a <p> element: 12/3
  • 53. Changing HTML Style • <html> <body> <p id="p2">Hello World!</p> <script> document.getElementById("p2").style.color = "blue"; </script> <p>The paragraph above was changed by a script.</p> </body> </html> 12/3
  • 54. Using Events • The HTML DOM allows you to execute code when an event occurs. • Events are generated by the browser when "things happen" to HTML elements:  An element is clicked on  The page has loaded  Input fields are changed • This example changes the style of the HTML element with id="id1", when the user clicks a button: 12/3
  • 55. Using Events <!DOCTYPE html> <html> <body> <h1 id="id1">My Heading 1</h1> <button type="button" onclick="document.getElementById('id1').style.color = 'red'"> Click Me!</button> </body> </html> 12/3