SlideShare une entreprise Scribd logo
1  sur  64
JS - JavaScript
Lecture - 1
Ajay Khatri
Senior Assistant Professor
Acropolis Institute ofTechnology & Research
www.ajaykhatri.in
www.ajaykhatri.in
Table of Contents
 What is DHTML?
 DHTMLTechnologies
 XHTML, CSS, JavaScript, DOM
 Introduction to JavaScript
 What is JavaScript
 Implementing JavaScript into Web pages
 In <head> part
 In <body> part
 In external .js file
www.ajaykhatri.in
Table of Contents (2)
 JavaScript Syntax
 JavaScript operators
 JavaScript DataTypes
 JavaScript Pop-up boxes
 alert, confirm and prompt
 Conditional and switch statements, loops and
functions
 Document Object Model
DHTML
Dynamic Behavior at the Client Side
www.ajaykhatri.in
What is DHTML?
 Dynamic HTML (DHTML)
 Makes possible a Web page to react and change
in response to the user’s actions
 DHTML = HTML + CSS + JavaScript
DHTML
XHTML CSS JavaScript DOM
www.ajaykhatri.in
DTHML = HTML + CSS + JavaScript
 HTML defines Web sites content through
semantic tags (headings, paragraphs, lists, …)
 CSS defines 'rules' or 'styles' for presenting
every aspect of an HTML document
 Font (family, size, color, weight, etc.)
 Background (color, image, position, repeat)
 Position and layout (of any object on the page)
 JavaScript defines dynamic behavior
 Programming logic for interaction with the
user, to handle events, etc.
JavaScript
Dynamic Behavior in a Web Page
www.ajaykhatri.in
JavaScript
 JavaScript is a front-end scripting language
developed by Netscape for dynamic content
 Lightweight, but with limited capabilities
 Can be used as object-oriented language
 Client-side technology
 Embedded in your HTML page
 Interpreted by theWeb browser
 Simple and flexible
 Powerful to manipulate the DOM
www.ajaykhatri.in
JavaScript Advantages
 JavaScript allows interactivity such as:
 Implementing form validation
 React to user actions, e.g. handle keys
 Changing an image on moving mouse over it
 Sections of a page appearing and disappearing
 Content loading and changing dynamically
 Performing complex calculations
 Custom HTML controls, e.g. scrollable table
 Implementing AJAX functionality
www.ajaykhatri.in
What Can JavaScript Do?
 Can handle events
 Can read and write HTML elements and
modify the DOM tree
 Can validate form data
 Can access / modify browser cookies
 Can detect the user’s browser and OS
 Can be used as object-oriented language
 Can handle exceptions
 Can perform asynchronous server calls (AJAX)
www.ajaykhatri.in
The First Script
first-script.html
<html>
<body>
<script type="text/javascript">
alert('Hello JavaScript!');
</script>
</body>
</html>
www.ajaykhatri.in
Another Small Example
small-example.html
<html>
<body>
<script type="text/javascript">
document.write('JavaScript rulez!');
</script>
</body>
</html>
www.ajaykhatri.in
Using JavaScript Code
 The JavaScript code can be placed in:
 <script> tag in the head
 <script> tag in the body – not recommended
 External files, linked via <script> tag the head
 Files usually have .js extension
 Highly recommended
 The .js files get cached by the browser
<script src="scripts.js" type="text/javscript">
<!– code placed here will not be executed! -->
</script>
www.ajaykhatri.in
JavaScript – When is Executed?
 JavaScript code is executed during the page
loading or when the browser fires an event
 All statements are executed at page loading
 Some statements just define functions that can
be called later
 Function calls or code can be attached as
"event handlers" via tag attributes
 Executed when the event is fired by the browser
<img src="logo.gif" onclick="alert('clicked!')" />
www.ajaykhatri.in
<html>
<head>
<script type="text/javascript">
function test (message) {
alert(message);
}
</script>
</head>
<body>
<img src="logo.gif"
onclick="test('clicked!')" />
</body>
</html>
Calling a JavaScript Function
from Event Handler – Example
image-onclick.html
www.ajaykhatri.in
Using External Script Files
 Using external script files:
 External JavaScript file:
<html>
<head>
<script src="sample.js" type="text/javascript">
</script>
</head>
<body>
<button onclick="sample()" value="Call JavaScript
function from sample.js" />
</body>
</html>
function sample() {
alert('Hello from sample.js!')
}
external-JavaScript.html
sample.js
The <script> tag is always empty.
The JavaScript
Syntax
www.ajaykhatri.in
JavaScript Syntax
 The JavaScript syntax is similar to C# and Java
 Operators (+, *, =, !=, &&, ++, …)
 Variables (typeless)
 Conditional statements (if, else)
 Loops (for, while)
 Arrays (my_array[]) and associative arrays
(my_array['abc'])
 Functions (can return value)
 Function variables (like the C# delegates)
www.ajaykhatri.in
DataTypes
 JavaScript data types:
 Numbers (integer, floating-point)
 Boolean (true / false)
 String type – string of characters
var length = 60; // Number
var lastName = "Khatri"; // String
var b = 44.5; // floating-point number
var isReading = true; // yes, I'm reading
www.ajaykhatri.in
DataTypes
 Arrays
 Associative arrays ( Object)
var my_array = [1, 5.3, "aaa"];
var my_hash = {a:2, b:3, c:"text"}; // Object
www.ajaykhatri.in
Everything is Object
 Every variable can be considered as object
 For example strings and arrays have member
functions:
var test = "some string";
alert(test[7]); // shows letter 'r'
alert(test.charAt(5)); // shows letter 's'
alert("test".charAt(1)); //shows letter 'e'
alert("test".substring(1,3)); //shows 'es'
var arr = [1,3,4];
alert (arr.length); // shows 3
arr.push(7); // appends 7 to end of array
alert (arr[3]); // shows 7
objects.html
www.ajaykhatri.in
String Operations
 The + operator joins strings
 What is "9" + 9?
 Converting string to number:
string1 = "fat ";
string2 = "cats";
alert(string1 + string2); // fat cats
alert("9" + 9); // 99
alert(parseInt("9") + 9); // 18
www.ajaykhatri.in
Arrays Operations and Properties
 Declaring new empty array:
 Declaring an array holding few elements:
 Appending an element / getting the last element:
 Reading the number of elements (array length):
 Finding element's index in the array:
var arr = new Array();
var arr = [1, 2, 3, 4, 5];
arr.push(3); //Add Elements
var element = arr.pop(); //Remove last Elements
arr.length;
arr.indexOf(1);
www.ajaykhatri.in
Standard Popup Boxes
 Alert box with text and [OK] button
 Just a message shown in a dialog box:
 Confirmation box
 Contains text, [OK] button and [Cancel] button:
 Prompt box
 Contains text, input field with default value:
alert("Some text here");
confirm("Are you sure?");
prompt ("enter amount", 10);
www.ajaykhatri.in
Sum of Numbers – Example
sum-of-numbers.html
<html>
<head>
<title>JavaScript Demo</title>
<script type="text/javascript">
function calcSum() {
value1 =
parseInt(document.mainForm.textBox1.value);
value2 =
parseInt(document.mainForm.textBox2.value);
sum = value1 + value2;
document.mainForm.textBoxSum.value = sum;
}
</script>
</head>
www.ajaykhatri.in
Sum of Numbers – Example (2)
sum-of-numbers.html (cont.)
<body>
<form name="mainForm">
<input type="text" name="textBox1" /> <br/>
<input type="text" name="textBox2" /> <br/>
<input type="button" value="Process"
onclick="javascript: calcSum()" />
<input type="text" name="textBoxSum"
readonly="readonly"/>
</form>
</body>
</html>
www.ajaykhatri.in
JavaScript Prompt – Example
prompt.html
price = prompt("Enter the price", "10.00");
alert('Price + VAT = ' + price * 1.2);
www.ajaykhatri.in
Greater than
<=
Symbol Meaning
>
< Less than
>= Greater than or equal to
Less than or equal to
== Equal
!= Not equal
Conditional Statement (if)
unitPrice = 1.30;
if (quantity > 100) {
unitPrice = 1.20;
}
www.ajaykhatri.in
Conditional Statement (if) (2)
 The condition may be of Boolean or integer type:
var a = 0;
var b = true;
if (typeof(a)=="undefined" || typeof(b)=="undefined") {
document.write("Variable a or b is undefined.");
}
else if (!a && b) {
document.write("a==0; b==true;");
} else {
document.write("a==" + a + "; b==" + b + ";");
}
conditional-statements.html
www.ajaykhatri.in
Switch Statement
 The switch statement works like in C#:
switch (variable) {
case 1:
// do something
break;
case 'a':
// do something else
break;
case 3.14:
// another code
break;
default:
// something completely different
}
switch-statements.html
www.ajaykhatri.in
Loops
 Like in C#
 for loop
 while loop
 do … while loop
var counter;
for (counter=0; counter<4; counter++) {
alert(counter);
}
while (counter < 5) {
alert(++counter);
} loops.html
www.ajaykhatri.in
Functions
 Code structure – splitting code into parts
 Data comes in, processed, result returned
function average(a, b, c)
{
var total;
total = a+b+c;
return total/3;
}
Parameters come
in here.
Declaring variables
is optional.Type is
never declared.
Value returned
here.
www.ajaykhatri.in
Function Arguments
and ReturnValue
 Functions are not required to return a value
 When calling function it is not obligatory to
specify all of its arguments
 The function has access to all the arguments
passed via arguments array
function sum() {
var sum = 0;
for (var i = 0; i < arguments.length; i ++)
sum += parseInt(arguments[i]);
return sum;
}
alert(sum(1, 2, 4)); functions-demo.html
Document Object
Model (DOM)
www.ajaykhatri.in
Document Object Model (DOM)
 Every HTML element is accessible via the
JavaScript DOM API
 Most DOM objects can be manipulated by the
programmer
 The event model lets a document to react when
the user does something on the page
 Advantages
 Create interactive pages
 Updates the objects of a page without reloading it
www.ajaykhatri.in
Accessing Elements
 Access elements via their ID attribute
 Via the name attribute
 Via tag name
 Returns array of descendant <img> elements of
the element "el"
var elem = document.getElementById("some_id")
var arr = document.getElementsByName("some_name")
var imgTags = el.getElementsByTagName("img")
www.ajaykhatri.in
DOM Manipulation
 Once we access an element, we can read and
write its attributes
function change(state) {
var lampImg = document.getElementById("lamp");
lampImg.src = "lamp_" + state + ".png";
var statusDiv =
document.getElementById("statusDiv");
statusDiv.innerHTML = "The lamp is " + state";
}
…
<img src="test_on.gif" onmouseover="change('off')"
onmouseout="change('on')" />
DOM-manipulation.html
www.ajaykhatri.in
Common Element Properties
 Most of the properties are derived from the
HTML attributes of the tag
 E.g. id, name, href, alt, title, src, etc…
 style property – allows modifying the CSS
styles of the element
 Corresponds to the inline style of the element
 Not the properties derived from embedded or
external CSS rules
 Example: style.width, style.marginTop,
style.backgroundImage
www.ajaykhatri.in
Common Element Properties (2)
 className – the class attribute of the tag
 innerHTML – holds all the entire HTML code
inside the element
 Read-only properties with information for the
current element and its state
 tagName, offsetWidth, offsetHeight,
scrollHeight, scrollTop, nodeType, etc…
www.ajaykhatri.in
Accessing Elements through
the DOMTree Structure
 We can access elements in the DOM through
some tree manipulation properties:
 element.childNodes
 element.parentNode
 element.nextSibling
 element.previousSibling
 element.firstChild
 element.lastChild
www.ajaykhatri.in
Accessing Elements through
the DOMTree – Example
 Warning: may not return what you expected
due to Browser differences
var el = document.getElementById('div_tag');
alert (el.childNodes[0].value);
alert (el.childNodes[1].
getElementsByTagName('span').id);
…
<div id="div_tag">
<input type="text" value="test text" />
<div>
<span id="test">test span</span>
</div>
</div> accessing-elements-demo.html
The HTML DOM
Event Model
www.ajaykhatri.in
The HTML DOM Event Model
 JavaScript can register event handlers
 Events are fired by the Browser and are sent to
the specified JavaScript event handler function
 Can be set with HTML attributes:
 Can be accessed through the DOM:
<img src="test.gif" onclick="imageClicked()" />
var img = document.getElementById("myImage");
img.onclick = imageClicked;
www.ajaykhatri.in
The HTML DOM Event Model (2)
 All event handlers receive one parameter
 It brings information about the event
 Contains the type of the event (mouse click, key
press, etc.)
 Data about the location where the event has
been fired (e.g. mouse coordinates)
 Holds a reference to the event sender
 E.g. the button that was clicked
www.ajaykhatri.in
The HTML DOM Event Model (3)
 Holds information about the state of [Alt], [Ctrl]
and [Shift] keys
 Some browsers do not send this object, but
place it in the document.event
 Some of the names of the event’s object
properties are browser-specific
www.ajaykhatri.in
Common DOM Events
 Mouse events:
 onclick, onmousedown, onmouseup
 onmouseover, onmouseout, onmousemove
 Key events:
 onkeypress, onkeydown, onkeyup
 Only for input fields
 Interface events:
 onblur, onfocus
 onscroll
www.ajaykhatri.in
Common DOM Events (2)
 Form events
 onchange – for input fields
 onsubmit
 Allows you to cancel a form submission
 Useful for form validation
 Miscellaneous events
 onload, onunload
 Allowed only for the <body> element
 Fires when all content on the page was loaded /
unloaded
www.ajaykhatri.in
onload Event – Example
 onload event
<html>
<head>
<script type="text/javascript">
function greet() {
alert("Loaded.");
}
</script>
</head>
<body onload="greet()" >
</body>
</html>
onload.html
The Built-In
Browser Objects
www.ajaykhatri.in
Built-in Browser Objects
 The browser provides some read-only data via:
 window
 The top node of the DOM tree
 Represents the browser's window
 document
 holds information the current loaded document
 screen
 Holds the user’s display properties
 browser
 Holds information about the browser
www.ajaykhatri.in
DOM Hierarchy – Example
window
navigator screen document history location
form
button form
form
www.ajaykhatri.in
Opening New Window – Example
 window.open()
var newWindow = window.open("", "sampleWindow",
"width=300, height=100, menubar=yes,
status=yes, resizable=yes");
newWindow.document.write(
"<html><head><title>
Sample Title</title>
</head><body><h1>Sample
Text</h1></body>");
newWindow.status =
"Hello folks";
window-open.html
www.ajaykhatri.in
The Navigator Object
alert(window.navigator.userAgent);
The navigator in the
browser window
The userAgent
(browser ID)
The browser
window
www.ajaykhatri.in
The Screen Object
 The screen object contains information about
the display
window.moveTo(0, 0);
x = screen.availWidth;
y = screen.availHeight;
window.resizeTo(x, y);
www.ajaykhatri.in
Document and Location
 document object
 Provides some built-in arrays of specific objects
on the currently loaded Web page
 document.location
 Used to access the currently open URL or
redirect the browser
document.links[0].href = "yahoo.com";
document.write(
"This is some <b>bold text</b>");
document.location = "http://www.yahoo.com/";
www.ajaykhatri.in
FormValidation – Example
function checkForm()
{
var valid = true;
if (document.mainForm.firstName.value == "") {
alert("Please type in your first name!");
document.getElementById("firstNameError").
style.display = "inline";
valid = false;
}
return valid;
}
…
<form name="mainForm" onsubmit="return checkForm()">
<input type="text" name="firstName" />
…
</form>
form-validation.html
www.ajaykhatri.in
The Math Object
 The Math object provides some mathematical
functions
for (i=1; i<=20; i++) {
var x = Math.random();
x = 10*x + 1;
x = Math.floor(x);
document.write(
"Random number (" +
i + ") in range " +
"1..10 --> " + x +
"<br/>");
}
math.html
www.ajaykhatri.in
The Date Object
 The Date object provides date / calendar
functions
var now = new Date();
var result = "It is now " + now;
document.getElementById("timeField")
.innerText = result;
...
<p id="timeField"></p>
dates.html
www.ajaykhatri.in
Timers: setTimeout()
 Make something happen (once) after a fixed
delay
var timer = setTimeout('bang()', 5000);
clearTimeout(timer);
5 seconds after this statement
executes, this function is called
Cancels the timer
www.ajaykhatri.in
Timers: setInterval()
 Make something happen repeatedly at fixed
intervals
var timer = setInterval('clock()', 1000);
clearInterval(timer);
This function is called
continuously per 1 second.
Stop the timer.
www.ajaykhatri.in
Timer – Example
<script type="text/javascript">
function timerFunc() {
var now = new Date();
var hour = now.getHours();
var min = now.getMinutes();
var sec = now.getSeconds();
document.getElementById("clock").value =
"" + hour + ":" + min + ":" + sec;
}
setInterval('timerFunc()', 1000);
</script>
<input type="text" id="clock" />
timer-demo.html
www.ajaykhatri.in
Questions?
Learn Javascript App
https://play.google.com/store/apps/details?id=learn.apps.javascriptprogramming
ThankYou

Contenu connexe

Tendances

Tendances (20)

Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
Lettering js
Lettering jsLettering js
Lettering js
 
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
 
PHPSpec BDD for PHP
PHPSpec BDD for PHPPHPSpec BDD for PHP
PHPSpec BDD for PHP
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?
 
(Parameterized) Roles
(Parameterized) Roles(Parameterized) Roles
(Parameterized) Roles
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
 
Let's write secure Drupal code! - Drupal Camp Poland 2019
Let's write secure Drupal code! - Drupal Camp Poland 2019Let's write secure Drupal code! - Drupal Camp Poland 2019
Let's write secure Drupal code! - Drupal Camp Poland 2019
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
Your code is not a string
Your code is not a stringYour code is not a string
Your code is not a string
 
Let's write secure Drupal code! DUG Belgium - 08/08/2019
Let's write secure Drupal code! DUG Belgium - 08/08/2019Let's write secure Drupal code! DUG Belgium - 08/08/2019
Let's write secure Drupal code! DUG Belgium - 08/08/2019
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
PHP security audits
PHP security auditsPHP security audits
PHP security audits
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
Introduction in php
Introduction in phpIntroduction in php
Introduction in php
 
Let's write secure Drupal code! - DrupalCamp London 2019
Let's write secure Drupal code! - DrupalCamp London 2019Let's write secure Drupal code! - DrupalCamp London 2019
Let's write secure Drupal code! - DrupalCamp London 2019
 

Similaire à Basics of Java Script (JS)

JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
BG Java EE Course
 
Java script
 Java script Java script
Java script
bosybosy
 

Similaire à Basics of Java Script (JS) (20)

JavaScript
JavaScriptJavaScript
JavaScript
 
JavaScript lesson 1.pptx
JavaScript lesson 1.pptxJavaScript lesson 1.pptx
JavaScript lesson 1.pptx
 
Wt unit 5
Wt unit 5Wt unit 5
Wt unit 5
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
 
Wt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technologyWt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technology
 
Wt unit 2 ppts client side technology
Wt unit 2 ppts client side technologyWt unit 2 ppts client side technology
Wt unit 2 ppts client side technology
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
FYBSC IT Web Programming Unit III Javascript
FYBSC IT Web Programming Unit III JavascriptFYBSC IT Web Programming Unit III Javascript
FYBSC IT Web Programming Unit III Javascript
 
Javascript
JavascriptJavascript
Javascript
 
UNIT 1 (7).pptx
UNIT 1 (7).pptxUNIT 1 (7).pptx
UNIT 1 (7).pptx
 
jQuery
jQueryjQuery
jQuery
 
Java script
 Java script Java script
Java script
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
FSJavaScript.ppt
FSJavaScript.pptFSJavaScript.ppt
FSJavaScript.ppt
 
jQuery basics
jQuery basicsjQuery basics
jQuery basics
 
Html JavaScript and CSS
Html JavaScript and CSSHtml JavaScript and CSS
Html JavaScript and CSS
 
jQuery
jQueryjQuery
jQuery
 
J Query Public
J Query PublicJ Query Public
J Query Public
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
Javascript
JavascriptJavascript
Javascript
 

Plus de Ajay Khatri (8)

Ajay khatri resume august 2021
Ajay khatri resume august 2021Ajay khatri resume august 2021
Ajay khatri resume august 2021
 
Lecture 1 Introduction C++
Lecture 1 Introduction C++Lecture 1 Introduction C++
Lecture 1 Introduction C++
 
Competitive Programming Guide
Competitive Programming GuideCompetitive Programming Guide
Competitive Programming Guide
 
Zotero : Personal Research Assistant
Zotero : Personal Research AssistantZotero : Personal Research Assistant
Zotero : Personal Research Assistant
 
Basics of C programming - day 2
Basics of C programming - day 2Basics of C programming - day 2
Basics of C programming - day 2
 
Introduction to HTML
Introduction to HTMLIntroduction to HTML
Introduction to HTML
 
Introduction To MySQL Lecture 1
Introduction To MySQL Lecture 1Introduction To MySQL Lecture 1
Introduction To MySQL Lecture 1
 
CSS Basics (Cascading Style Sheet)
CSS Basics (Cascading Style Sheet)CSS Basics (Cascading Style Sheet)
CSS Basics (Cascading Style Sheet)
 

Dernier

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Dernier (20)

Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 

Basics of Java Script (JS)

  • 1. JS - JavaScript Lecture - 1 Ajay Khatri Senior Assistant Professor Acropolis Institute ofTechnology & Research www.ajaykhatri.in
  • 2. www.ajaykhatri.in Table of Contents  What is DHTML?  DHTMLTechnologies  XHTML, CSS, JavaScript, DOM  Introduction to JavaScript  What is JavaScript  Implementing JavaScript into Web pages  In <head> part  In <body> part  In external .js file
  • 3. www.ajaykhatri.in Table of Contents (2)  JavaScript Syntax  JavaScript operators  JavaScript DataTypes  JavaScript Pop-up boxes  alert, confirm and prompt  Conditional and switch statements, loops and functions  Document Object Model
  • 4. DHTML Dynamic Behavior at the Client Side
  • 5. www.ajaykhatri.in What is DHTML?  Dynamic HTML (DHTML)  Makes possible a Web page to react and change in response to the user’s actions  DHTML = HTML + CSS + JavaScript DHTML XHTML CSS JavaScript DOM
  • 6. www.ajaykhatri.in DTHML = HTML + CSS + JavaScript  HTML defines Web sites content through semantic tags (headings, paragraphs, lists, …)  CSS defines 'rules' or 'styles' for presenting every aspect of an HTML document  Font (family, size, color, weight, etc.)  Background (color, image, position, repeat)  Position and layout (of any object on the page)  JavaScript defines dynamic behavior  Programming logic for interaction with the user, to handle events, etc.
  • 8. www.ajaykhatri.in JavaScript  JavaScript is a front-end scripting language developed by Netscape for dynamic content  Lightweight, but with limited capabilities  Can be used as object-oriented language  Client-side technology  Embedded in your HTML page  Interpreted by theWeb browser  Simple and flexible  Powerful to manipulate the DOM
  • 9. www.ajaykhatri.in JavaScript Advantages  JavaScript allows interactivity such as:  Implementing form validation  React to user actions, e.g. handle keys  Changing an image on moving mouse over it  Sections of a page appearing and disappearing  Content loading and changing dynamically  Performing complex calculations  Custom HTML controls, e.g. scrollable table  Implementing AJAX functionality
  • 10. www.ajaykhatri.in What Can JavaScript Do?  Can handle events  Can read and write HTML elements and modify the DOM tree  Can validate form data  Can access / modify browser cookies  Can detect the user’s browser and OS  Can be used as object-oriented language  Can handle exceptions  Can perform asynchronous server calls (AJAX)
  • 11. www.ajaykhatri.in The First Script first-script.html <html> <body> <script type="text/javascript"> alert('Hello JavaScript!'); </script> </body> </html>
  • 12. www.ajaykhatri.in Another Small Example small-example.html <html> <body> <script type="text/javascript"> document.write('JavaScript rulez!'); </script> </body> </html>
  • 13. www.ajaykhatri.in Using JavaScript Code  The JavaScript code can be placed in:  <script> tag in the head  <script> tag in the body – not recommended  External files, linked via <script> tag the head  Files usually have .js extension  Highly recommended  The .js files get cached by the browser <script src="scripts.js" type="text/javscript"> <!– code placed here will not be executed! --> </script>
  • 14. www.ajaykhatri.in JavaScript – When is Executed?  JavaScript code is executed during the page loading or when the browser fires an event  All statements are executed at page loading  Some statements just define functions that can be called later  Function calls or code can be attached as "event handlers" via tag attributes  Executed when the event is fired by the browser <img src="logo.gif" onclick="alert('clicked!')" />
  • 15. www.ajaykhatri.in <html> <head> <script type="text/javascript"> function test (message) { alert(message); } </script> </head> <body> <img src="logo.gif" onclick="test('clicked!')" /> </body> </html> Calling a JavaScript Function from Event Handler – Example image-onclick.html
  • 16. www.ajaykhatri.in Using External Script Files  Using external script files:  External JavaScript file: <html> <head> <script src="sample.js" type="text/javascript"> </script> </head> <body> <button onclick="sample()" value="Call JavaScript function from sample.js" /> </body> </html> function sample() { alert('Hello from sample.js!') } external-JavaScript.html sample.js The <script> tag is always empty.
  • 18. www.ajaykhatri.in JavaScript Syntax  The JavaScript syntax is similar to C# and Java  Operators (+, *, =, !=, &&, ++, …)  Variables (typeless)  Conditional statements (if, else)  Loops (for, while)  Arrays (my_array[]) and associative arrays (my_array['abc'])  Functions (can return value)  Function variables (like the C# delegates)
  • 19. www.ajaykhatri.in DataTypes  JavaScript data types:  Numbers (integer, floating-point)  Boolean (true / false)  String type – string of characters var length = 60; // Number var lastName = "Khatri"; // String var b = 44.5; // floating-point number var isReading = true; // yes, I'm reading
  • 20. www.ajaykhatri.in DataTypes  Arrays  Associative arrays ( Object) var my_array = [1, 5.3, "aaa"]; var my_hash = {a:2, b:3, c:"text"}; // Object
  • 21. www.ajaykhatri.in Everything is Object  Every variable can be considered as object  For example strings and arrays have member functions: var test = "some string"; alert(test[7]); // shows letter 'r' alert(test.charAt(5)); // shows letter 's' alert("test".charAt(1)); //shows letter 'e' alert("test".substring(1,3)); //shows 'es' var arr = [1,3,4]; alert (arr.length); // shows 3 arr.push(7); // appends 7 to end of array alert (arr[3]); // shows 7 objects.html
  • 22. www.ajaykhatri.in String Operations  The + operator joins strings  What is "9" + 9?  Converting string to number: string1 = "fat "; string2 = "cats"; alert(string1 + string2); // fat cats alert("9" + 9); // 99 alert(parseInt("9") + 9); // 18
  • 23. www.ajaykhatri.in Arrays Operations and Properties  Declaring new empty array:  Declaring an array holding few elements:  Appending an element / getting the last element:  Reading the number of elements (array length):  Finding element's index in the array: var arr = new Array(); var arr = [1, 2, 3, 4, 5]; arr.push(3); //Add Elements var element = arr.pop(); //Remove last Elements arr.length; arr.indexOf(1);
  • 24. www.ajaykhatri.in Standard Popup Boxes  Alert box with text and [OK] button  Just a message shown in a dialog box:  Confirmation box  Contains text, [OK] button and [Cancel] button:  Prompt box  Contains text, input field with default value: alert("Some text here"); confirm("Are you sure?"); prompt ("enter amount", 10);
  • 25. www.ajaykhatri.in Sum of Numbers – Example sum-of-numbers.html <html> <head> <title>JavaScript Demo</title> <script type="text/javascript"> function calcSum() { value1 = parseInt(document.mainForm.textBox1.value); value2 = parseInt(document.mainForm.textBox2.value); sum = value1 + value2; document.mainForm.textBoxSum.value = sum; } </script> </head>
  • 26. www.ajaykhatri.in Sum of Numbers – Example (2) sum-of-numbers.html (cont.) <body> <form name="mainForm"> <input type="text" name="textBox1" /> <br/> <input type="text" name="textBox2" /> <br/> <input type="button" value="Process" onclick="javascript: calcSum()" /> <input type="text" name="textBoxSum" readonly="readonly"/> </form> </body> </html>
  • 27. www.ajaykhatri.in JavaScript Prompt – Example prompt.html price = prompt("Enter the price", "10.00"); alert('Price + VAT = ' + price * 1.2);
  • 28. www.ajaykhatri.in Greater than <= Symbol Meaning > < Less than >= Greater than or equal to Less than or equal to == Equal != Not equal Conditional Statement (if) unitPrice = 1.30; if (quantity > 100) { unitPrice = 1.20; }
  • 29. www.ajaykhatri.in Conditional Statement (if) (2)  The condition may be of Boolean or integer type: var a = 0; var b = true; if (typeof(a)=="undefined" || typeof(b)=="undefined") { document.write("Variable a or b is undefined."); } else if (!a && b) { document.write("a==0; b==true;"); } else { document.write("a==" + a + "; b==" + b + ";"); } conditional-statements.html
  • 30. www.ajaykhatri.in Switch Statement  The switch statement works like in C#: switch (variable) { case 1: // do something break; case 'a': // do something else break; case 3.14: // another code break; default: // something completely different } switch-statements.html
  • 31. www.ajaykhatri.in Loops  Like in C#  for loop  while loop  do … while loop var counter; for (counter=0; counter<4; counter++) { alert(counter); } while (counter < 5) { alert(++counter); } loops.html
  • 32. www.ajaykhatri.in Functions  Code structure – splitting code into parts  Data comes in, processed, result returned function average(a, b, c) { var total; total = a+b+c; return total/3; } Parameters come in here. Declaring variables is optional.Type is never declared. Value returned here.
  • 33. www.ajaykhatri.in Function Arguments and ReturnValue  Functions are not required to return a value  When calling function it is not obligatory to specify all of its arguments  The function has access to all the arguments passed via arguments array function sum() { var sum = 0; for (var i = 0; i < arguments.length; i ++) sum += parseInt(arguments[i]); return sum; } alert(sum(1, 2, 4)); functions-demo.html
  • 35. www.ajaykhatri.in Document Object Model (DOM)  Every HTML element is accessible via the JavaScript DOM API  Most DOM objects can be manipulated by the programmer  The event model lets a document to react when the user does something on the page  Advantages  Create interactive pages  Updates the objects of a page without reloading it
  • 36. www.ajaykhatri.in Accessing Elements  Access elements via their ID attribute  Via the name attribute  Via tag name  Returns array of descendant <img> elements of the element "el" var elem = document.getElementById("some_id") var arr = document.getElementsByName("some_name") var imgTags = el.getElementsByTagName("img")
  • 37. www.ajaykhatri.in DOM Manipulation  Once we access an element, we can read and write its attributes function change(state) { var lampImg = document.getElementById("lamp"); lampImg.src = "lamp_" + state + ".png"; var statusDiv = document.getElementById("statusDiv"); statusDiv.innerHTML = "The lamp is " + state"; } … <img src="test_on.gif" onmouseover="change('off')" onmouseout="change('on')" /> DOM-manipulation.html
  • 38. www.ajaykhatri.in Common Element Properties  Most of the properties are derived from the HTML attributes of the tag  E.g. id, name, href, alt, title, src, etc…  style property – allows modifying the CSS styles of the element  Corresponds to the inline style of the element  Not the properties derived from embedded or external CSS rules  Example: style.width, style.marginTop, style.backgroundImage
  • 39. www.ajaykhatri.in Common Element Properties (2)  className – the class attribute of the tag  innerHTML – holds all the entire HTML code inside the element  Read-only properties with information for the current element and its state  tagName, offsetWidth, offsetHeight, scrollHeight, scrollTop, nodeType, etc…
  • 40. www.ajaykhatri.in Accessing Elements through the DOMTree Structure  We can access elements in the DOM through some tree manipulation properties:  element.childNodes  element.parentNode  element.nextSibling  element.previousSibling  element.firstChild  element.lastChild
  • 41. www.ajaykhatri.in Accessing Elements through the DOMTree – Example  Warning: may not return what you expected due to Browser differences var el = document.getElementById('div_tag'); alert (el.childNodes[0].value); alert (el.childNodes[1]. getElementsByTagName('span').id); … <div id="div_tag"> <input type="text" value="test text" /> <div> <span id="test">test span</span> </div> </div> accessing-elements-demo.html
  • 43. www.ajaykhatri.in The HTML DOM Event Model  JavaScript can register event handlers  Events are fired by the Browser and are sent to the specified JavaScript event handler function  Can be set with HTML attributes:  Can be accessed through the DOM: <img src="test.gif" onclick="imageClicked()" /> var img = document.getElementById("myImage"); img.onclick = imageClicked;
  • 44. www.ajaykhatri.in The HTML DOM Event Model (2)  All event handlers receive one parameter  It brings information about the event  Contains the type of the event (mouse click, key press, etc.)  Data about the location where the event has been fired (e.g. mouse coordinates)  Holds a reference to the event sender  E.g. the button that was clicked
  • 45. www.ajaykhatri.in The HTML DOM Event Model (3)  Holds information about the state of [Alt], [Ctrl] and [Shift] keys  Some browsers do not send this object, but place it in the document.event  Some of the names of the event’s object properties are browser-specific
  • 46. www.ajaykhatri.in Common DOM Events  Mouse events:  onclick, onmousedown, onmouseup  onmouseover, onmouseout, onmousemove  Key events:  onkeypress, onkeydown, onkeyup  Only for input fields  Interface events:  onblur, onfocus  onscroll
  • 47. www.ajaykhatri.in Common DOM Events (2)  Form events  onchange – for input fields  onsubmit  Allows you to cancel a form submission  Useful for form validation  Miscellaneous events  onload, onunload  Allowed only for the <body> element  Fires when all content on the page was loaded / unloaded
  • 48. www.ajaykhatri.in onload Event – Example  onload event <html> <head> <script type="text/javascript"> function greet() { alert("Loaded."); } </script> </head> <body onload="greet()" > </body> </html> onload.html
  • 50. www.ajaykhatri.in Built-in Browser Objects  The browser provides some read-only data via:  window  The top node of the DOM tree  Represents the browser's window  document  holds information the current loaded document  screen  Holds the user’s display properties  browser  Holds information about the browser
  • 51. www.ajaykhatri.in DOM Hierarchy – Example window navigator screen document history location form button form form
  • 52. www.ajaykhatri.in Opening New Window – Example  window.open() var newWindow = window.open("", "sampleWindow", "width=300, height=100, menubar=yes, status=yes, resizable=yes"); newWindow.document.write( "<html><head><title> Sample Title</title> </head><body><h1>Sample Text</h1></body>"); newWindow.status = "Hello folks"; window-open.html
  • 53. www.ajaykhatri.in The Navigator Object alert(window.navigator.userAgent); The navigator in the browser window The userAgent (browser ID) The browser window
  • 54. www.ajaykhatri.in The Screen Object  The screen object contains information about the display window.moveTo(0, 0); x = screen.availWidth; y = screen.availHeight; window.resizeTo(x, y);
  • 55. www.ajaykhatri.in Document and Location  document object  Provides some built-in arrays of specific objects on the currently loaded Web page  document.location  Used to access the currently open URL or redirect the browser document.links[0].href = "yahoo.com"; document.write( "This is some <b>bold text</b>"); document.location = "http://www.yahoo.com/";
  • 56. www.ajaykhatri.in FormValidation – Example function checkForm() { var valid = true; if (document.mainForm.firstName.value == "") { alert("Please type in your first name!"); document.getElementById("firstNameError"). style.display = "inline"; valid = false; } return valid; } … <form name="mainForm" onsubmit="return checkForm()"> <input type="text" name="firstName" /> … </form> form-validation.html
  • 57. www.ajaykhatri.in The Math Object  The Math object provides some mathematical functions for (i=1; i<=20; i++) { var x = Math.random(); x = 10*x + 1; x = Math.floor(x); document.write( "Random number (" + i + ") in range " + "1..10 --> " + x + "<br/>"); } math.html
  • 58. www.ajaykhatri.in The Date Object  The Date object provides date / calendar functions var now = new Date(); var result = "It is now " + now; document.getElementById("timeField") .innerText = result; ... <p id="timeField"></p> dates.html
  • 59. www.ajaykhatri.in Timers: setTimeout()  Make something happen (once) after a fixed delay var timer = setTimeout('bang()', 5000); clearTimeout(timer); 5 seconds after this statement executes, this function is called Cancels the timer
  • 60. www.ajaykhatri.in Timers: setInterval()  Make something happen repeatedly at fixed intervals var timer = setInterval('clock()', 1000); clearInterval(timer); This function is called continuously per 1 second. Stop the timer.
  • 61. www.ajaykhatri.in Timer – Example <script type="text/javascript"> function timerFunc() { var now = new Date(); var hour = now.getHours(); var min = now.getMinutes(); var sec = now.getSeconds(); document.getElementById("clock").value = "" + hour + ":" + min + ":" + sec; } setInterval('timerFunc()', 1000); </script> <input type="text" id="clock" /> timer-demo.html