920 likes | 1.07k Vues
JavaScript is a versatile and lightweight scripting language designed for adding interactivity to HTML pages. It allows developers to create dynamic content, respond to user events, and manipulate web elements directly within the browser without requiring a compilation step. Originally named LiveScript, JavaScript is widely supported across all major browsers and can be embedded within HTML using `<script>` tags. By understanding variables, functions, and events, developers can create engaging user experiences while ensuring compatibility with older browsers.
E N D
SWE 444Internet and Web Application Development(javaScript) Mr.AbdullahMrian
Overview • A "scripting" language for HTML pages - a scripting • language is a lightweight programming language. • Embed code in HTML pages so they are downloaded • directly to browser. • The browser interprets and executes the script (it is not compiled). • Was designed to add interactivity to HTML pages. • Everyone can use JavaScript without purchasing a license. • Supported by all major browsers.
…Overview • Do not declare data types for variables. • Scripts can manipulate "browser objects:" • HTML form elements • Images • Frames • etc. • For security – cannot write to disk (when run on a client)
Abilities • Generating HTML content dynamically. • Monitoring and responding to user events. • Validate forms before submission. • Manipulate HTTP cookies. • Interact with the frames and windows of the browser. • Customize pages to suit users.
It is not Java • JavaScript is not Java, or even related to Java. • The original name for JavaScript was “LiveScript”. • The name was changed when Java became popular. • Statements in JavaScript resemble statements in Java,because both languages borrowed heavily from the C language. • JavaScript is seldom used to write complete “programs”. • Instead, small bits of JavaScript are used to add functionality to HTML pages. • JavaScript is often used in conjunction with HTML “forms”.
….It is not Java • JavaScript has some features that resemble features in Java: • JavaScript has Objects and primitive data types. • JavaScript has qualified names; for example: document.write("Hello World"); • JavaScript has Events and event handlers. • Exception handling in JavaScript is almost the same as in Java. • JavaScript has some features unlike anything in Java: • Variable names are untyped: the type of a variable depends on the value it is currently holding. • Objects and arrays are defined in quite a different way. • JavaScript has with statements and a new kind of for statement.
What is a script? • A program or sequence of instructions that is interpreted or carried out by another program. • A program embedded in an HTML document. • Scripts + HTML DHTML (dynamic HTML).
What is JavaScript? • Created by Netscape • Originally called LiveWire then LiveScript • A client-side scripting language: • Client-side refers to the fact that it is executed in the client (browser) that the viewer is using. • A server-side language is one that runs on the Web server : • Examples: PHP, ASP.
Client and Server • JavaScript can be used: • On the client side • On the server • More lightweight and reliable on clients than Java (Applets). • Useful for developing interactive interface (Dynamic HTML).
Example • JavaScript code is included within <script> tags: • Notes: • The type attribute is to allow you to use other scripting languages (but JavaScript is the default). • This simple code does the same thing as just putting • <h1>Hello World!</h1> in the same place in the HTML document. • The semicolon at the end of the JavaScript statement is optional: • You need semicolons if you put two or more statements on the same line. • It’s probably a good idea to keep using semicolons.
Dealing with old browsers • Some old browsers do not recognize script tags: • These browsers will ignore the script tags but will display the included JavaScript. • To get old browsers to ignore the whole thing, use: • The <!-- introduces an HTML comment. • To get JavaScript to ignore the HTML close comment, -->, the // starts a JavaScript comment, which extends to the end of the line.
The <script>…</script> tag <script type="text/javascript"> . . . </script> The code for the script is contained in the <script>…</script> tag
Displaying text • The document.write() method writes a string of text to the browser <script type="text/javascript"> document.write("<h1>Hello, world!</h1>"); </script>
document.write() Ends in a semicolon document.write("<h1>Hello,world!</h1>"); Enclosed in quotes -- denotes a "string"
Getting User Input • Use the prompt() function • Will display a pop-up window asking the user to enter data • Examples: name = prompt("What is your name?"); payRate = prompt("Enter your pay rate: "); score = prompt("Please enter the score: ");
Comments in JavaScript • Two types of comments • Single line • Uses two forward slashes (i.e. //) • Multiple line • Uses /* and */
Single Line Comment Example <script type="text/javascript"> // This is my JavaScript comment document.write("<h1>Hello!</h1>"); </script>
Multiple Line Comment Example <script type="text/javascript"> /* This is a multiple line comment. * The star at the beginning of this line is optional. * So is the star at the beginning of this line. */ document.write("<h1>Hello!</h1>"); </script>
Find the Bug! <script type="text/javascript"> /* This is my JavaScript comment * that spans more than 1 line. * document.write("<h1>Hello!</h1>"); </script>
JavaScript Statements <html> <head><title>My Page</title></head> <body> <script language="JavaScript"> document.write('This is my first JavaScript Page'); </script> </body> </html>
HTML written inside JavaScript JavaScript Statements <html> <head><title>My Page</title></head> <body> <script language= "JavaScript"> document.write('<h1>This is my first JavaScript Page</h1>'); </script> </body> </html>
JavaScript Statements <html> <head><title>My Page</title></head> <body> <p> <a href="myfile.html" onMouseover="window.alert('Hello');"> My Page</a> </p> </body> </html> JavaScript written inside HTML An Event
Example Statements <script language="JavaScript"> window.prompt('Enter your name:',''); </script> <form> <input type="button" Value="Press" onClick="window.alert('Hello');"> </form> Note quotes: " and '
Input and Output • The input functions available are: • prompt (message, defaultvalue) takes an input and returns it to the JavaScript program • confirm (question) asks the user to confirm an input value and return a Boolean value • The output functions available are: • document.write (string) • alert (string)
HTML Forms and JavaScript • JavaScript is very good at processing user input in the web browser • HTML <form> elements receive input <form action="…"method="…"name="…"…> any number of form elements and plain HTML </form>
HTML Form Elements <input type="text"/> <input type="password"/> <input type="button" value="Label"/> <input type="submit"/> <input type="reset"/> <input type="image" src="smiley.jpg"/> <input type="checkbox"/> <input type="radio" name="sex" value="Male"/> <input type="radio" name="sex" value="Female"/> <textarea rows="3" cols="40"> This is the initial text spread over two lines </textarea> <select> <option>First</option> <option>Second</option> </select> <input type="file"/>
Naming Form Elements in HTML <form name="addressform"> Name: <input name="yourname"><br /> Phone: <input name="phone"><br /> Email: <input name="email"><br /> </form>
Forms and JavaScript document.formname.elementname.value document.addressform.yourname.value document.addressform.phone.value document.addressform.email.value
Using Form Data Personalising an alert box <form name="alertform"> Enter your name: <input type="text" name="yourname"> <input type="button" value= "Go" onClick="window.alert('Hello ' + document.alertform.yourname.value);"> </form>
<html> <body> <form> <input type=button name=btn1 value="Click A" onClick="alert('button A was clicked');" > <input type=button name=btn2 value="Click B" onClick="alert('button B was clicked');" > </form> </body> </html>
Variables • Variables names must begin with a letter or underscore • Variable names are case-sensitive • Variables are untyped (they can hold values of any type) • The word var is optional (but it’s good style to use it)
Which Are Legal Identifiers? • AREA 3D • lucky*** num45 • Last-Chance #values • x_yt3 pi • num+ %done • area_under_the_curve
Declaring Variables • Before using a variable, you need to declare it. • The declaration statement includes the varkeyword and the name of the variable. • Examples of variable declarations: var ball; var ball, area; var area;
More About Variables • In JavaScript variables can hold four basic types of values • Numbers • i.e. 40, 15.5, 700 • Strings • i.e. "Hello, World!", "Linux is cool!" • Booleans • i.e. true, false • Null • i.e. null
length 7 diameter 5.9 message “Hello!” walletEmpty true Using Variables: Initialization • Variables may be be given initial values, or initialized, when declared. Examples: var length = 7; var diameter = 5.9; var message = "Hello!"; var walletEmpty = true;
Using Variables: Assignment • Uses the assignment operator = Examples: diameter = 5.9 ; area = length * width ;
JavaScript Arithmetic Operators Given that y=5, the table below explains the arithmetic operators:
JavaScript Assignment Operators Given thatx=10andy=5, the table below explains the assignment operators:
Adding Strings and Numbers x=5+5;document.write(x);x="5"+"5";document.write(x);x=5+"5";document.write(x);x="5"+5;document.write(x); 10 55 55 55
Conditional Statements • if statement • if...else statement • if...else if....else statement • switch statement
Example var d = new Date();var time = d.getHours();if (time < 10) { document.write("Good morning!"); }else { document.write("Good day!"); }
Gotcha! = versus == var a = 2; if(a = 1) /* semantic (logic) error! */ { alert("a is one"); } else if(a == 2) { alert("a is two"); } else { alert("a is " + a); }
Multiple Selection with if if (day == 0 ) { alert ("Sunday") ; } if (day == 1 ) { alert ("Monday") ; } if (day == 2) { alert ("Tuesday") ; } if (day == 3) { alert ("Wednesday") ; }
Multiple Selection with if-else if (day == 0 ) { alert ("Sunday") ; } else if (day == 1 ) { alert ("Monday") ; } else if (day == 2) { alert ("Tuesday") ; } else if (day == 3) { alert ("Wednesday") ; } else if (day == 4) { alert ("Thursday") ; } else if (day == 5) { alert ("Friday") ; } else if (day == 6) { alert ("Saturday") ; } else { alert ("Error - invalid day.") ; }
switch Example switch ( day ) { case 0: alert ("Sunday") ; break ; case 1: alert ("Monday") ; break ; case 2: alert ("Tuesday") ; break ; case 3: alert ("Wednesday") ; break ; case 4: alert ("Thursday") ; break ; case 5: alert ("Friday") ; break ; case 6: alert ("Saturday") ; break ; default: alert ("Error -- invalid day.") ; }