Sie sind auf Seite 1von 36

Web Design and

development
Lecture 8
Course Instructor: Wardah Mahmood
Email Id: wardah.mahmood@riphah.edu.pk
DHTML
• Dynamic HTML (DHTML)
• Makes possible for a Web page to react and change in response to the user’s actions
• DHTML = HTML + CSS + JavaScript

DHTML

XHTML CSS JavaScript DOM


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.
Examples are 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
• JavaScript is the programming language of HTML and the Web.
• JavaScript is one of the 3 languages all web developers must learn:
   1. HTML to define the content of web pages.
   2. CSS to specify the layout of web pages.
   3. JavaScript to program the behavior of web pages.
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 the Web browser
• Simple and flexible
• Powerful to manipulate the DOM
What is JavaScript?
• Unlike most programming languages, the JavaScript language has no concept of input or
output.

• It is designed to run as a scripting language in a host environment, and it is up to the


host environment to provide mechanisms for communicating with the outside world.

• JavaScript is

• an object oriented dynamic language with types and operators,


• standard built-in objects, and methods.
What is JavaScript?
• One of the key differences is that JavaScript does not have classes; instead, the class
functionality is accomplished by object prototypes.

• The other main difference is that functions are objects, giving functions the capacity to
hold executable code and be passed around like any other object.
• JavaScript is Usually Embedded Directly into Web Pages
• Contained within a web page and integrates with its HTML/CSS content
Why use JavaScript?
• JavaScript can React to Events
• Do something on mouse click
• Dynamic Content
• JavaScript can read and write HTML elements
• Get Information about a User's Computer
• Browser type
• Perform Calculations
• Form validation
• Store and Retrieve Data on the User's Computer
• Cookies
JavaScript
Examples and practices
Basic examples
<body>
<script type="text/javascript">
alert('Hello JavaScript!');
</script>
</body>

<body>
<script type="text/javascript">
document.write('JavaScript rulez!');
</script>
</body>
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
When is JavaScript 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!')" />


Calling a JavaScript Function from
Event Handler – Example
<html>
<head>
<script type="text/javascript">
function test (message) {
alert(message);
}
</script>
</head>

<body>
<img src="logo.gif"
onclick="test('clicked!')" />
</body>
</html>
Using External Script Files
• Using external script files:
<head>
<script src="sample.js" type="text/javascript">
</script>
</head>
<body>
<button onclick="sample()" value="Call JavaScript
function from sample.js" />
</body>
• External JavaScript file:

function sample() {
alert('Hello from sample.js!')
}
JavaScript Syntax
The JavaScript syntax is similar to C# and Java
• Operators (+, *, =, !=, &&, ++, …)
• Variables
• 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)
var myHeading = document.querySelector('h1');
myHeading.textContent = 'Hello world!';
JavaScript Statements
• JavaScript is Case Sensitive
• Therefore watch your capitalization closely when you write JavaScript statements, create or
call variables, objects and functions.
• A JavaScript statement is a command to a browser. The purpose of the command is to tell
the browser what to do.
• It is normal to add a semicolon at the end of each executable statement. Using semicolons
makes it possible to write multiple statements on one line.
JavaScript Variables
• The general rules for constructing names for variables (unique identifiers) are:
• Names can contain letters, digits, underscores, and dollar signs.
• Names must begin with a letter
• Names can also begin with $ and _
• Names are case sensitive (y and Y are different variables)
• You declare a JavaScript variable with the var keyword:
• var carName;
carName = "Volvo";
• var carName = "Volvo";
• var carName = "Volvo", carType=“Sedan";

See: http://www.w3schools.com/js/js_variables.asp
Data types
JavaScript data types:
• Numbers (integer, floating-point)
• Boolean (true / false)
• String type – string of characters
var myName = "You can use both single or double
quotes for strings";
• Arrays
var my_array = [1, 5.3, "aaa"];
• Associative arrays (hash tables)
var my_hash = {a:2, b:3, c:"text"};
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
19
String Operations
• The + operator joins strings

string1 = "fat ";


string2 = "cats";
alert(string1 + string2); // fat cats
• What is "9" + 9?

alert("9" + 9); // 99

• Converting string to number:

alert(parseInt("9") + 9); // 18

20
Arrays Operations and Properties
• Declaring new empty array:
var arr = new Array();

• Declaring an array holding few elements:


var arr = [1, 2, 3, 4, 5];
• Appending an element / getting the last element:
arr.push(3);
var element = arr.pop();
• Reading the number of elements (array length):
arr.length;
• Finding element's index in the array:
arr.indexOf(1);
21
Standard Popup Boxes
• Alert box with text and [OK] button
• Just a message shown in a dialog box:
alert("Some text here");
• Confirmation box
• Contains text, [OK] button and [Cancel] button:
confirm("Are you sure?");
• Prompt box
• Contains text, input field with default value:
price = prompt("Enter the price", "10.00");
alert('Price + VAT = ' + price * 1.2);

22
Conditional statements
unitPrice = 1.30;
if (quantity > 100) {
unitPrice = 1.20;
}

Symbol Meaning
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal
!= Not equal
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
}
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);
}
While Loop
var i=0;
while (i<=5)
{
document.write("The number is " + i);
document.write("<br />");
i++;
}

See: http://www.w3schools.com/js/js_loop_while.asp
Do While Loop
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
while (i<=5);

See: http://www.w3schools.com/js/js_loop_while.asp
Javascript Functions
JavaScript Functions
• A function contains code that will be executed by an event or by a call to the function.
• You may call a function from anywhere within a page (or even from other pages if
the function is embedded in an external .js file).
• Functions can be defined both in the <head> and in the <body> section of a
document. However, to assure that a function is read/loaded by the browser
before it is called, it could be wise to put functions in the <head> section.
• Note: A function with no parameters must include the parentheses () after the function
name.
• Note: The word function must be written in lowercase letters, otherwise a JavaScript error
occurs! Also note function name is case-sensitive.

See: http://www.w3schools.com/js/js_functions.asp
Functions
• Code structure – splitting code into parts
• Data comes in, processed, result returned

Parameters come in
function average(a, b, c) here.
{
var total; Declaring variables is
total = a+b+c; optional. Type is never
return total/3; declared.
}
Value returned here.
Function arguments and return
value
• 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));
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>
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>
JavaScript Variable Scope
• Variables declared within a JavaScript function, become local to the function.
• A global variable has global scope: All scripts and functions on a web page can access it. 
• If you assign a value to a variable that has not been declared, it will automatically become a
global variable.

var x="For Everyone"; // global


function dosomething()
{
var y="For Function Only"; // local
z="Also For Everyone"; // global
}
JavaScript Events
• HTML elements have special attributes called event attributes
• JavaScript functions can be set as event handlers
• When you interact with the element, the function will execute
• onclick is just one of many HTML event attributes
• For a comprehensive list of Event Attributes:
• http://www.w3schools.com/jsref/dom_obj_event.asp

See: http://www.w3schools.com/js/js_events.asp
Event Attributes
• onblur An element loses focus
• onchange The content of a field changes
• onclick Mouse clicks an object
• ondblclick Mouse double-clicks an object
• onfocus An element gets focus
• onload A page or image is finished loading
• onmousedown A mouse button is pressed
• onmouseup A mouse button is released
• onselect Text is selected
• onunload The user exits the page

See: http://www.w3schools.com/jsref/dom_obj_event.asp

Das könnte Ihnen auch gefallen