1 Javascript CS , Spring 2010
2 What is Javascript ? Browser scripting language Dynamic page creation Interactive Embedded into HTML pages Javascript is NOT Java Different syntax Different programming concepts Javascript runs on client-side (browser) only
Adding Javascript to HTML All Javascript code must be inside Old browsers do not support Javascript Example: 3 <!-- document.write(“ Hello World ”); -->
Programming concept No static types Everything is an associative array Every variable can hold attributes No access limitations (i.e no private attributes) Functions are variables Dynamic binding Inheritance is possible (though complicated and incomplete) 4
Variables example var x = 1; // define a numeral variable x = “123”; // x is now a string x = new Object(); // x is now an object x.attr = “val”; // x now has the attribute ‘attr’ x.f = function() { document.write(“a”); }; // x now has a function named ‘f’ x.f(); // f is invoked 5
Functions Defined by the keyword ‘function’ No return type and no argument types Can be invoked with any number of arguments Example: 6 function f(x) { alert(x); } f(‘abc’); // result will be an alert box with ‘abc’ f(); // result will be an alert box with ‘undefined’ f(‘abc’, ‘edf’); // result will be an alert box with ‘abc’
Execution Javascript code may be executed in 2 different cases: Upon parsing the page, when the browser encounters javascript code not inside a function Example: document.write(‘ Hi ’); Events (next slide) 7
Events Javascript can be activated on certain events When a page is loaded When a button is clicked When a form is submitted And many more … Example: function f() { alert(‘clicked !’); } 8
Events Consider the following example click me Which javascript function should be invoked first? Netscape answer: f Firefox answer: default g, can be changed to f Microsoft Explorer: g 9
Events (form submission example) function validate_required(field, alerttxt) { if (field.value==null|| field.value==“”) { alert(alerttxt); return false; } return true; } function validate_form(form) { if (validate_required(form. ,” is requred”)==false) { return false; } return true; } 10
Events (form submission cont) 11
DOM Javascript has built in access to the html document DOM tree Every element in the html document can be removed or modified New elements can be inserted to the html document dynamically 12
DOM Example function f() { var elmt = document.createElement('h1'); var txtNode = document.createTextNode('new element'); elmt.appendChild(txtNode); document.getElementById('someId').appendChild(elmt); } 13
References and tutorials