c5 javascript

24
Client-side Scripting Languages Introduction to Javascript

Upload: vlad-posea

Post on 01-Nov-2014

44 views

Category:

Education


1 download

DESCRIPTION

 

TRANSCRIPT

Page 1: C5 Javascript

Client-side Scripting Languages

Introduction to Javascript

Page 2: C5 Javascript

Plan of the course

• Javascript – Why, When, What

• How to include Javascript in HTML

• Javascript syntax

• Document Object Model

• Examples

Page 3: C5 Javascript

Javascript – Why, When, What

• At first we had only simple text + links + images pages

• “live” pages were required by the market • Netscape invented “LiveScript” in 1995• Later renamed to Javascript• Javascript – run on browsers, access

dynamically to the html page• The language was (is) interpreted usually

in different way by the browsers

Page 4: C5 Javascript

Include Javascript into HTML

• Script inclus in pagina html– <script type=”text/javascript”>– //cod script– </script>

• Script inclus intr-un fisier exterior– <script src=”fisier_sursa.js”></script>

Page 5: C5 Javascript

When does the code run

• If the script tag is included in the <head> tag– The script is executed when the page is

loaded – before actually rendering it

• If the script is included in the body page– The script is executed when the markup is

found

Page 6: C5 Javascript

Javascript Syntax

• Very similar with C & Java• No types for variables

– Declare variables using the term var– var x=5, y=7;

• Functions are declared using the function keyword– function sum(x,y)– { var rez=x+y; return rez;}

• Calling functions is the same as in C/Java– var suma=sum(2,5);

Page 7: C5 Javascript

Javascript objects

• Objects have – methods (functions)– Properties

• Example– var student={nume: "ion", an:2, note:{mate:9, pc:8}};– alert(student.nume +"<br>" );– alert(student.an +"<br>");– var nota– var student={nume: "ion", an:2, note:{mate:9, pc:8}};

Page 8: C5 Javascript

Javascript predefined objects

• Math– http://www.w3schools.com/jsref/jsref_obj_math.asp

• String– http://www.w3schools.com/jsref/jsref_obj_string.asp

• Array– http://www.w3schools.com/jsref/jsref_obj_array.asp

• Date– http://www.w3schools.com/jsref/jsref_obj_date.asp

Page 9: C5 Javascript

Examples<script type="text/javascript">

function printValue() //declare a function{var x=Math.random()*10; //compute the value of x as a random value between 0 and 10alert(x); //display an alert containing the value of xvar y="a random text"; //create a variable of type stringalert(y.length); //display an alert containing the length of y

//!!! length is a property and not a methodalert(y.substr(0,5)); //compute and display as an alert the substring of y between the first and the 5th characteralert(x+" "+y.length+“ “+y.substr(5,y.length));

//display as an alert the string formed by x, length of y and the substring formed from the 5th character of y until the last one

}</script>

Page 10: C5 Javascript

Javascript example - followup

• String concatenation operator “+”

• The alert is used for displaying information during development. NOT to be used in applications

• Objects can have methods like y.substr(0,5) and properties like y.length

• All types of variables are declared using var

Page 11: C5 Javascript

Events

• HTML elements can detect when the user interacts with them

• Examples of interactions– Mouse over (mouse out)– Click– Key pressed– Blur– change

• We can add javascript code to handle every interaction

Page 12: C5 Javascript

Events examples

<script type=“text/javascript”>

function youClicked(element)

{this.innerHTML="you clicked this element";}

function youMousedOver()

{alert("mouse over detected"); }

</script>

<h1 onclick="alert('youclicked');youClicked(this);" onmouseover="youMousedOver()"> Introduction dans la programmation web</h1>

Page 13: C5 Javascript

Javascript Events

• Why we need and what is the “this” pointer

Html element

User

interacts

event1event2

Event1 associated javascript function

In order for this function to be able to modify the element with which the user interacted we need to pass it a reference to the object

“this” is the reference to the object on which the event is handled

Page 14: C5 Javascript

DOM

• DOM=Document Object Model

• DOM = a way to access the elements of a HTML page

Page 15: C5 Javascript

DOM

• The DOM tree contains nodes which can be– Html elements– Text

• The tree elements can be accessed– By traversing the tree (See Data structures course)– By accessing them directly by name

(getElementsByTagName)– By accessing them directly by id (getElementById)– Addressing them directly (as in an array)

• The root of the DOM tree is the document

Page 16: C5 Javascript

Methods and properties• document.write(“text”)

– Adds the “text” to the given page– If the page is finished loading it rewrites it– Example<script type="text/javascript">

function printValue(){var x=Math.random()*10;alert(x);var y="a random text";alert(y.length);alert(y.substr(0,5));alert(x+" "+y.length+"!!!"+y.substr(5,y.length));document.write(x+" "+y.length+"!!!"+y.substr(5,y.length));}</script>

Page 17: C5 Javascript

DOM Methods and properties

• getElementsByTagName– Returns an array of elements with a given name– The we need to know the position of the element we

need to modify inside the arrayfunction modifySecondH1()

{var

headersArray=document.getElementsByTagName("h1"); //retrieves all the elements whose names are h1

//elements’ numbering in the array starts at 0headersArray[1].innerHTML=Math.random()*5;

}

Page 18: C5 Javascript

DOM Methods and properties

• document.getElementById– The most used method to access an element of a

html page– We have to be careful to set ids for the elementsfunction modifyFirstH1(){//retrieve the element with the id h1id1var h1Element=document.getElementById("h1id1");//set the HTML value for the documenth1Element.innerHTML="new title";}

Page 19: C5 Javascript

DOM objects methods and properties

• Direct access to the element• Predefined collections

– Forms– Links – Images

• document.forms[0].username.value – accesses the first form in the document and sets the value property for the username input

Page 20: C5 Javascript

Example – using javascript to validate forms

• When a form is submitted we need to validate it first on the client-side

• The form should be validated before submitting

• The event should be added to the submit button

• For example we want to check if 2 passwords have the same value and if the username is longer than 4 characters

Page 21: C5 Javascript

Validate forms with Javascript – example (I)

function validateForm(){var usernameElement=document.getElementById("username");var passwordElement=document.getElementById("password");var rePasswordElement=document.getElementById("repassword");if(passwordElement.value!=rePasswordElement.value || passwordElement.value.length==0){alert("please make sure the password is entered the same twice");return;}

if (usernameElement.value.length<4){alert("please make sure the username is longer than 4 letters");return; }document.forms[0].submit();}

Page 22: C5 Javascript

Example of form validation with Javascript (II)

<form action="script.php" method="POST">nom d'utilisateur<input type="text" id="username" /><br/>mot de passe<input type="password" id="password" /> <br/>mot de passe encore une fois <input id="repassword" type="password"> <br/><input type="button" value="send" onclick="validateForm();"/></form>

Page 23: C5 Javascript

Javascript debugging

• Firebug – extension for Firefox– Allows debugging of scripts– Step by step execution– Adding breakpoints– Watch expressions– Visualize the DOM tree

Page 24: C5 Javascript

Javascript debugging example