05 – Java Script (1) Informatics Department Parahyangan Catholic University.
-
Upload
aleesha-patterson -
Category
Documents
-
view
220 -
download
2
Transcript of 05 – Java Script (1) Informatics Department Parahyangan Catholic University.
Pemrograman Berbasis Web05 – Java Script (1)
Informatics DepartmentParahyangan Catholic University
Java Script
JavaScript is the programming language that adds interactivity and custom behaviors to our sites.
It is a client-side scripting language (runs on the user’s machine and not on the server).
Java Script
JavaScript has nothing to do with Java.
It was created by Brendan Eich at Netscape in 1995 and originally named “LiveScript” .
For the sake of marketing, “LiveScript” became “JavaScript”.
JavaScript and HTML
Java Script is placed inside <script> … </script> tag
Example: <html><head>
<title>Hello World</title></head><body>
<script type="text/javascript">document.write("Hello World")
</script><noscript>
Your browser doesn't support or has disabled JavaScript
</noscript></body></html>
Script Location
JS can be placed anywhere within HTML document
It is usually placed inside <head> section to make sure critical functions are ready
to use by other scripts in the document so that JS can writes meta tag into the
<head> section (because the location of your script is the part of the document it writes to by default)
Including JS Files
We can include files of JavaScript code either from our own website or from anywhere on the Internet.
Example:<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="http://someserver.com/script.js"></script>
Debugging JavaScript Errors Web browsers provide a JavaScript console as
part of their developer tools.
Keyboard shortcut for opening console (Win): Chrome: Ctrl + Shift + J Firefox: Ctrl + Shift + K Internet Explorer: F12 then click on “Console”
tab Safari: Ctrl + Shift + C
(need to enable the “Show Develop menu in menu bar” setting in “Advanced” preferences pane)
Syntaxes
According to the TIOBE index, Java, Java Script, and PHP are all heavily influenced by the C Programming Language, thus they all share many similarities.
Comment
Single-line comment: // This is a comment
Multiline comments:/* This is a sectionof multiline commentsthat will not beinterpreted */
Semicolon
JavaScript generally does not require semicolons for one statement on a line.
The following is valid: x += 10
However, more than one statement on a line needs to be separated with semicolons:x += 10; y -= 5; z = 0
In doubt, use a semicolon.
Two Types of Value
Fixed values (called literals) Numbers : written with or without decimals10.501001
String: written within double or single quotes"John Doe"'John Doe'
Variable values (called variables) JavaScript has dynamic types. This means
that the same variable can be used as different types.
Variable
Use var keyword to create a variable.Example: var x;
Naming rules: the first character must be a letter, an
underscore (_), or a dollar sign ($). Subsequent characters may be letters, digits,
underscores, or dollar signs.
All JavaScript identifiers are case sensitive
Global & Local Variables
Global variables are ones defined outside of any functions (or within functions, but defined without the var keyword).
Example:<script>function test(){ a = 123 // Global scope var b = 456 // Local scope if (a == 123) var c = 789 // Local scope}</script>
Dynamic Type
var x; // Now x is undefinedvar x = 5; // Now x is a Numbervar x = "John"; // Now x is a String
What is the value of x ?var x = 16 + "Volvo";var x = 16 + 4 + "Volvo";var x = "Volvo" + 16 + 4;
Forcing Variable Type
n = "123"n *= 1 // Convert 'n' into a numbern = 123n += "" // Convert 'n' into a string
If n cannot be converted to number, it returns NaN
value
parseInt() Function
The parseInt() function parses a string and returns the first integer found. It returns NaN if the string doesn’t start with a number.
Leading and trailing spaces are allowed.
Syntax: parseInt(string,radix) The radix parameter is optional and is
used to specify which numeral system to be used.
parseInt() Function
Example: returns
parseInt("10.00")parseInt("10.33")parseInt("34 45 66")parseInt("40 years")parseInt("He was 40")parseInt("10",8)parseInt("0x10")parseInt("10",16)
10103440NaN81616
parseFloat() Function
The parseFloat() function parses a string and returns the first floating point number found. It returns NaN if the string doesn’t start with a number.
Leading and trailing spaces are allowed.
Syntax: parseFloat(string)
parseFloat() Function
Example: returns
parseFloat("10.00")parseFloat("10.33")parseFloat("34 45 66")parseFloat(" 60 ")parseFloat("40 years")parseFloat("He was 40")
1010.33346040NaN
Arrays
An array can contain string or numeric data, as well as other arrays.
To assign values to an array, use the following syntax (which in this case creates an array of strings):
toys = ['bat', 'ball', 'whistle', 'puzzle', 'doll']
Arrays
To create a multidimensional array, nest smaller arrays within a larger one. Example:face = [['R','G','Y'], ['W','R','O'], ['Y','W','G']]
or:top = ['R', 'G', 'Y']mid = ['W', 'R', 'O']bot = ['Y', 'W', 'G']face = [top, mid, bot]
Array index starts from zero. Example: to access letter ‘O’, use face[1][2].
Operators
Arithmetic: Addition + Subtraction - Multiplication * Division / Modulus % Increment ++ Decrement --
floating point division
means +1
means -1
Operators
Assignment: = += -= *= /= %=
Logical: && And || Or ! Not
Operators
Comparison: == equal to != not equal > greater than >= greater than or equal to < less than <= less than or equal to === equal to (and of the same type) !== not equal to (and of the same
type)
(10 == '10') is true(10 === '10') is false
(10 != '10') is false(10 !== '10') is true
The Document Object Model (DOM)
This breaks down the parts of an HTML document into discrete objects, each with its own properties and methods and each subject to JavaScript’s control.
The HTML DOM is a standard for how to get, change, add, or delete HTML elements
The Document Object Model (DOM)
The Document Object Model (DOM)
Example:<html><head> <title>Link Test</title></head><body> <a id="mylink" href="http://mysite.com">Click me</a> </body></html>
<script> url = document.links.mylink.href document.write('The URL is ' + url)</script>
The Document Object Model (DOM)
We can use getElementById() method to fetch an element by its id
<html><head> <title>Link Test</title></head><body> <a id="mylink" href="http://mysite.com">Click me</a> </body></html>
<script> url = document.getElementById("mylink").href document.write('The URL is ' + url)</script>
DOM HTML Element
Several ways to find HTML element(s): by idvar x = document.getElementById("intro");
by tag namevar x = document.getElementById("main");
var y = x.getElementsByTagName("p");
by class namedocument.getElementsByClassName("intro");
DOM HTML Element
Several ways to find HTML element(s): by HTML object collections
This example finds the form element with id="frm1", in the forms collection, and displays all element values:
var x = document.getElementById("frm1");var text = "";var i;for (i = 0; i < x.length; i++) { text += x.elements[i].value + "<br>";}
Changing HTML
To modify the content of an HTML element, use the innerHTML property
To change the value of an HTML attribute, use this syntax:document.getElementById(id).attribute=n
ew value
document.getElementById("p1").innerHTML = "New text!";
document.getElementById("myImage").src="landscape.jpg";
Changing HTML
To change the style of an HTML element, use this syntax:document.getElementById(id).style.property=ne
w styledocument.getElementById("p2").style.color = "blue";
Java Script Function
The general syntax for a function is:function function_name([parameter [, ...]]){
statements}
<script>function displayItems(v1, v2, v3, v4, v5){ document.write(v1 + "<br />"); document.write(v2 + "<br />"); document.write(v3 + "<br />"); document.write(v4 + "<br />"); document.write(v5 + "<br />");}displayItems("Dog", "Cat", "Pony", "Hamster", "Tortoise");</script>
Java Script Function
The arguments array gives you the flexibility to handle a variable number of arguments<script>
function displayItems(){ for(j=0 ; j<displayItems.arguments.length ; ++j) document.write(displayItems.arguments[j] + "<br />");}</script>
Events
Some examples of HTML events: An HTML web page has finished loading An HTML input field was changed An HTML button was clicked
JavaScript lets you execute code when events are detected.
Events
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
Syntax:<HTML_tag event_name="JavaScript">
Common Events
onclickThe user clicks an HTML element
onchangeAn HTML element has been changed
onmouseoverThe user moves the mouse over an HTML element
onmouseoutThe user moves the mouse away from an HTML element
onkeydown / onkeyupThe user pushes / releases a keyboard key
onloadThe browser has finished loading the page
Events
Example:<html><body>
<button onclick="getElementById('demo').innerHTML=Date()">The time is?</button>
<p id="demo"></p>
</body></html>
Events
Example:<html><body>
<button onclick="this.innerHTML=Date()">The time is?</button>
</body></html>
Events
Example:<html><body> <p>Click the button to display the date.</p> <button onclick="displayDate()">The time is?</button> <p id="demo"></p></body></html>
<script>function displayDate() { document.getElementById("demo").innerHTML = Date();}</script>
Events
Example:<div onmouseover="mOver(this)" onmouseout="mOut(this)" style="background-color:#D94A38;width:120px;">Mouse Over Me</div>
<script>function mOver(obj) { obj.innerHTML = "Thank You"}
function mOut(obj) { obj.innerHTML = "Mouse Over Me"}</script>