Note: Java and JavaScript are two completely different languages in both concept and design!

Similar documents
INTRODUCTION TO WEB DEVELOPMENT AND HTML. Lecture 15: JavaScript loops, Objects, Events - Spring 2011

CSS The web browser uses its own resources, and eases the burden on the server. It has fewer features than server side scripting.

Introduction to JavaScript

What is Java Script? Writing to The HTML Document. What Can JavaScript do? CMPT 165: Java Script

The first sample. What is JavaScript?

About the Tutorial. Audience. Prerequisites. Copyright and Disclaimer

COMS 469: Interactive Media II

What Is JavaScript? A scripting language based on an object-orientated programming philosophy.

Try the following example using the Try it option available at the top right corner of the below sample code box

LECTURE-2. Functions review HTML Forms. Arrays Exceptions Events. CS3101: Scripting Languages: Javascript Ramana Isukapalli

PES DEGREE COLLEGE BANGALORE SOUTH CAMPUS 1 K.M. before Electronic City, Bangalore WEB PROGRAMMING Solution Set II

LECTURE-3. Exceptions JS Events. CS3101: Programming Languages: Javascript Ramana Isukapalli

Javascript Methods. concat Method (Array) concat Method (String) charat Method (String)

Javascript Hierarchy Objects Object Properties Methods Event Handlers. onload onunload onblur onfocus

PIC 40A. Lecture 10: JS: Wrapper objects, Input and Output, Control structures, random numbers. Copyright 2011 Jukka Virtanen UCLA 1 04/24/17

Lecture 14. Introduction to JavaScript. Mr. Mubashir Ali Lecturer (Dept. of Computer Science)

Try the following example using the Try it option available at the top right corner of the below sample code box

JavaScript Introduction

JAVASCRIPT BASICS. JavaScript Math Functions. The Math functions helps you to perform mathematical tasks

Index. syntax, 140 tostring() method, 141 valueof() method, 141 break statement, 185

BJavaScript Core Reference

Chapter 12 - JavaScript: Objects

CITS1231 Web Technologies. JavaScript Math, String, Array, Number, Debugging

448 JavaScript/JScript: Objects Chapter 13

Such JavaScript Very Wow

Client-Side Web Technologies. JavaScript Part I

Events: another simple example

Chapter 2. Outline. Simple C++ Programs

Product Price Formula extension for Magento2. User Guide

Princeton University COS 333: Advanced Programming Techniques A Subset of JavaScript

The Number object. to set specific number types (like integer, short, In JavaScript all numbers are 64bit floating point

A.A. 2008/09. Why introduce JavaScript. G. Cecchetti Internet Software Technologies

Pearson Education Limited Edinburgh Gate Harlow Essex CM20 2JE England and Associated Companies throughout the world

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial

How to put a JavaScript into an HTML document

Chapter 1 Introduction to Computers and the Internet

<form>. input elements. </form>

Princeton University COS 333: Advanced Programming Techniques A Subset of JavaScript

Fundamentals of Website Development

JAVASCRIPT BASICS. Handling Events In JavaScript. In programing, event-driven programming could be a programming

Princess Nourah bint Abdulrahman University. Computer Sciences Department

New Perspectives on Creating Web Pages with HTML. Tutorial Objectives

a Why JavaScript? jonkv interactivity on the web CGI JavaScript Java Applets Netscape LiveScript JavaScript 1: Example

COMS 469: Interactive Media II

By the end of this section of the practical, the students should be able to:

More on new. Today s Goals. CSCI 2910 Client/Server-Side Programming. Creating/Defining Objects. Creating/Defining Objects (continued)

Session 6. JavaScript Part 1. Reading

Object Overview. Built-in Objects -- String (cont d) Built-in Objects -- String &6&7XWRULDO -DYD6UFLSW (GZDUG;LD )HEUXDU\ Built-in objects

710 Index Attributes, 127 action attribute, 263 assigning, bottom attribute, domain name attribute, 481 expiration date attribute, 480 8

Chapter 12. JavaScript 1: Basic Scripting Table of Contents

CSC 1214: Object-Oriented Programming

Session 16. JavaScript Part 1. Reading

ANSI C Programming Simple Programs

Full file at Tutorial 2: Working with Operators and Expressions

Chapter 4: Basic C Operators

CSC Web Programming. Introduction to JavaScript

CGS 3066: Spring 2015 JavaScript Reference

Key features. Nothing to do with java It is the Client-side scripting language Designed to add interactivity to HTML pages

JavaScript s role on the Web

Methods CSC 121 Fall 2014 Howard Rosenthal

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

Engineering Problem Solving with C++, Etter/Ingber

Maths Functions User Manual

CT 229 Java Syntax Continued

CISH-6510 Web Application Design and Development. Overview of JavaScript. Overview

Introduction to DHTML

Chapter 4 Basics of JavaScript

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Like most objects, String objects need to be created before they can be used. To create a String object, we can write

Computer Components. Software{ User Programs. Operating System. Hardware

JavaScript Handling Events Page 1

Web Programming and Design. MPT Junior Cycle Tutor: Tamara Demonstrators: Aaron, Marion, Hugh

Q1. What is JavaScript?

JScript Reference. Contents

Methods CSC 121 Fall 2016 Howard Rosenthal

3. Java - Language Constructs I

1$ 5 ! $ 6 4 * Source: 0 "!*! 0! * 8 97 ?!$ 5 0 *! 4! $ 0 : * ' () 7;7 7<7

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

JAVASCRIPT. Ajax Technology in Web Programming. Sergio Luján Mora. DLSI - Universidad de Alicante 1. Basic syntax and features

Introduction to Python, Cplex and Gurobi

Just add an HTML comment tag <!-- before the first JavaScript statement, and an end-of comment tag --> after the last JavaScript statement, like this:

JavaScript Introduction

Program Fundamentals

Lecture 3: The Basics of JavaScript. Background. Needs for Programming Capability. Origin of JavaScript. Using Client-side JavaScript

Unit 20 - Client Side Customisation of Web Pages. Week 4 Lesson 5 Fundamentals of Scripting

C++ Programming Lecture 11 Functions Part I

C++ Overview. Chapter 1. Chapter 2

Computer Components. Software{ User Programs. Operating System. Hardware

Methods CSC 121 Spring 2017 Howard Rosenthal

COMP 202 Java in one week

Web Programming/Scripting: JavaScript

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

write vs. writeln Prompting as Page Loads Today s Goals CSCI 2910 Client/Server-Side Programming Intermediate File vs. HTML Output

DC71 INTERNET APPLICATIONS JUNE 2013

UNIT-4 JAVASCRIPT. Prequisite HTML/XHTML. Origins

Place User-Defined Functions in the HEAD Section

DM550 Introduction to Programming part 2. Jan Baumbach.

Want to add cool effects like rollovers and pop-up windows?

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

JavaScript. History. Adding JavaScript to a page. CS144: Web Applications

Transcription:

Java Script: JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language A scripting language is a lightweight programming language JavaScript is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary compilation) Everyone can use JavaScript without purchasing a license Note: Java and JavaScript are two completely different languages in both concept and design! Advantages: JavaScript can interact with events - A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML element JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the visitor's computer Disadvantages Security Issues Javascript snippets, once appended onto web pages execute on client servers immediately and therefore can also be used to exploit the user's system. While a certain restriction is set by modern web standards on browsers, malicious code can still be executed complying with the restrictions set. Javascript rendering varies The HTML <script> tag is used to insert a JavaScript into an HTML page. <html> <body> document.write("hello World!"); </body> </html> To insert a JavaScript into an HTML page, we use the <script> tag. Inside the <script> tag we use the type attribute to define the scripting language. So, the and tells where the JavaScript starts and The document.write command is a standard JavaScript command for writing output to a page. By entering the document.write command between the <script> and tags, the browser will recognize it as a JavaScript command and execute the code line. In this case the browser will write Hello World! to the page:

JavaScript s in a page will be executed immediately while the page loads into the browser. This is not always what we want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event. Identifier:. Integer 2. Floating point numbers 3. Strings 4. Booleans Expression: 2 <HTML> <Body> <script> var a=0; var b=20; var c=a+b; var d="jaipal"; document.write(c+d); </BODY> </HTML> <HTML> <BODY> <script> a=0; b=20; c=a+b; d="jaipal"; document.write(c+d); </BODY> </HTML> Java Key Words: abstract boolean break byte case catch char class const continue debugger default delete do double else enum export extends false final finally float for function goto if implements import in instanceof int interface long native new null package private protected public return short static super switch synchronized this throw throws transient true try typeof var void volatile while with JavaScript Assignment Operators: Operator Example Same As Result = x=y x=5 += x+=y x=x+y x=5 -= x-=y x=x-y x=5 *= x*=y x=x*y x=50 /= x/=y x=x/y x=2 %= x%=y x=x%y x=0

3 Java Script Operators: Operator Description Example Result + Addition x=y+2 x=7 y=5 - Subtraction x=y-2 x=3 y=5 * Multiplication x=y*2 x=0 y=5 / Division x=y/2 x=2.5 y=5 % Modulus (division x=y%2 x= y=5 remainder) ++ Increment x=++y x=6 y=6 x=y++ x=5 y=6 -- Decrement x=--y x=4 y=4 x=y-- x=5 y=4 The + Operator Used on Strings(String Oprator) The + operator can also be used to add string variables or text values together. To add two or more string variables together, use the + operator. txt="what a very"; txt2="nice day"; txt3=txt+txt2; Comparison Operators Comparison operators are used in logical statements to determine equality or difference between variables or values. Given that x=5, the table below explains the comparison operators: Operator Description Example == is equal to x==8 is false === is exactly equal to (value and type) x===5 is true x==="5" is false!= is not equal x!=8 is true > is greater than x>8 is false < is less than x<8 is true >= is greater than or equal to x>=8 is false <= is less than or equal to x<=8 is true Logical Operators Logical operators are used to determine the logic between variables or values. Given that x=6 and y=3, the table below explains the logical operators: Operator Description Example && and (x < 0 && y > ) is true or (x==5 y==5) is false! not!(x==y) is true

4 Standard Event Attributes HTML 4 added the ability to let events trigger actions in a browser, like starting a JavaScript when a user clicks on an element. <body> and <frameset> Events The two attributes below can only be used in <body> or <frameset>: Attribute Value Description onload script Script to be run when a document load onunload script Script to be run when a document unload Form Events The attributes below can be used in form elements: Attribute Value Description onblur script Script to be run when an element loses focus onchange script Script to be run when an element changes onfocus script Script to be run when an element gets focus onreset script Script to be run when a form is reset onselect script Script to be run when an element is selected onsubmit script Script to be run when a form is submitted Image Events The attribute below can be used with the img element: Attribute Value Description onabort script Script to be run when loading of an image is interrupted Keyboard Events Valid in all elements except base, bdo, br, frame, frameset, head, html, iframe, meta, param, script, style, and title. Attribute Value Description onkeydown script Script to be run when a key is pressed onkeypress script Script to be run when a key is pressed and released onkeyup script Script to be run when a key is released

Mouse Events Valid in all elements except base, bdo, br, frame, frameset, head, html, iframe, meta, param, script, style, and title. Attribute Value Description onclick script Script to be run on a mouse click ondblclick script Script to be run on a mouse double-click onmousedown script Script to be run when mouse button is pressed onmousemove script Script to be run when mouse pointer moves onmouseout script Script to be run when mouse pointer moves out of an element onmouseover script Script to be run when mouse pointer moves over an element onmouseup script Script to be run when mouse button is released 5 Conditional Statements In JavaScript we have the following conditional statements: if statement - use this statement to execute some code only if a specified condition is true if...else statement - use this statement to execute some code if the condition is true and another code if the condition is false if...else if...else statement - use this statement to select one of many blocks of code to be executed switch statement - use this statement to select one of many blocks of code to be executed If Statement Use the if statement to execute some code only if a specified condition is true. if (condition) code to be executed if condition is true The JavaScript Switch Statement Use the switch statement to select one of many blocks of code to be executed. switch(n) case : execute code block break; case 2: execute code block 2 break; default: code to be executed if n is different from case and 2

6 If...else if...else Statement Use the if...else if...else statement to select one of several blocks of code to be executed. if (condition) code to be executed if condition is true else if (condition2) code to be executed if condition2 is true else code to be executed if condition and condition2 are not true JavaScript Loops In JavaScript, there are two different kind of loops: for - loops through a block of code a specified number of times while - loops through a block of code while a specified condition is true The for Loop The for loop is used when you know in advance how many times the script should run. for (variable=startvalue;variable<=endvalue;variable=vari able+increment) code to be executed The while Loop The while loop loops through a block of code while a specified condition is true. while (variable<=endvalue) code to be executed The do...while Loop The do...while loop is a variant of the while loop. This loop will execute the block of code ONCE, and then it will repeat the loop as long as the specified condition is true. do code to be executed while (variable<=endvalue); JavaScript Popup Boxes. Alert Box 2. Confirm Box 3. Prompt Box Alert Box An alert box is often used if you want to make sure information comes through to the user. When an alert box pops up, the user will have to click "OK" to proceed. alert("sometext"); Example <html> <head> function show_alert() alert("i am an alert box!"); </head> <body> <input type="button" onclick="show_alert()" value="show alert box" />

7 </body> </html> Confirm Box A confirm box is often used if you want the user to verify or accept something. When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false. confirm("sometext"); Example <html> <head> function show_confirm() var r=confirm("press a button"); if (r==true) document.write("you pressed OK!"); else document.write("you pressed Cancel!"); </head> <body> <input type="button" onclick="show_confirm()" value="show confirm box" /> </body> </html> Prompt Box A prompt box is often used if you want the user to input a value before entering a page. When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null. prompt("sometext","defaultvalue"); Example <html> <head> function show_prompt() var name=prompt("please enter your name","harry Potter"); if (name!=null && name!="") document.write("hello " + name + "! How are you today?"); </head> <body> <input type="button" onclick="show_prompt()" value="show prompt box" /> </body> </html>

8 String Object Methods Method Description charat() charcodeat() concat() fromcharcode() indexof() lastindexof() match() replace() search() slice() split() substr() substring() tolowercase() touppercase() valueof() Returns the character at the specified index Returns the Unicode of the character at the specified index Joins two or more strings, and returns a copy of the joined strings Converts Unicode values to characters Returns the position of the first found occurrence of a specified value in a string Returns the position of the last found occurrence of a specified value in a string Searches for a match between a regular expression and a string, and returns the matches Searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substring Searches for a match between a regular expression and a string, and returns the position of the match Extracts a part of a string and returns a new string Splits a string into an array of substrings Extracts the characters from a string, beginning at a specified start position, and through the specified number of character Extracts the characters from a string, between two specified indices Converts a string to lowercase letters Converts a string to uppercase letters Returns the primitive value of a String object Math Object Methods Method Description abs(x) acos(x) asin(x) atan(x) atan2(y,x) ceil(x) cos(x) exp(x) floor(x) log(x) max(x,y,z,...,n) min(x,y,z,...,n) Returns the absolute value of x Returns the arccosine of x, in radians Returns the arcsine of x, in radians Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians Returns the arctangent of the quotient of its arguments Returns x, rounded upwards to the nearest integer Returns the cosine of x (x is in radians) Returns the value of E x Returns x, rounded downwards to the nearest integer Returns the natural logarithm (base E) of x Returns the number with the highest value Returns the number with the lowest value

9 pow(x,y) Returns the value of x to the power of y random() Returns a random number between 0 and round(x) Rounds x to the nearest integer sin(x) Returns the sine of x (x is in radians) sqrt(x) Returns the square root of x tan(x) Returns the tangent of an angle Date Object Methods Method Description getdate() Returns the day of the month (from -3) getday() Returns the day of the week (from 0-6) getfullyear() Returns the year (four digits) gethours() Returns the hour (from 0-23) getmilliseconds() Returns the milliseconds (from 0-999) getminutes() Returns the minutes (from 0-59) getmonth() Returns the month (from 0-) getseconds() Returns the seconds (from 0-59) gettime() Returns the number of milliseconds since midnight Jan, 970 gettimezoneoffset() Returns the time difference between GMT and local time, in minutes getutcdate() Returns the day of the month, according to universal time (from -3) getutcday() Returns the day of the week, according to universal time (from 0-6) getutcfullyear() Returns the year, according to universal time (four digits) getutchours() Returns the hour, according to universal time (from 0-23) getutcmilliseconds() Returns the milliseconds, according to universal time (from 0-999) getutcminutes() Returns the minutes, according to universal time (from 0-59) getutcmonth() Returns the month, according to universal time (from 0-) getutcseconds() Returns the seconds, according to universal time (from 0-59) getyear() parse() Deprecated. Use the getfullyear() method instead Parses a date string and returns the number of milliseconds since midnight of January, 970 setdate() Sets the day of the month (from -3) setfullyear() Sets the year (four digits) sethours() Sets the hour (from 0-23) setmilliseconds() Sets the milliseconds (from 0-999) setminutes() Set the minutes (from 0-59) setmonth() Sets the month (from 0-) setseconds() Sets the seconds (from 0-59) settime() Sets a date and time by adding or subtracting a specified number of milliseconds

to/from midnight January, 970 setutcdate() Sets the day of the month, according to universal time (from -3) setutcfullyear() Sets the year, according to universal time (four digits) setutchours() Sets the hour, according to universal time (from 0-23) setutcmilliseconds() Sets the milliseconds, according to universal time (from 0-999) setutcminutes() Set the minutes, according to universal time (from 0-59) setutcmonth() Sets the month, according to universal time (from 0-) setutcseconds() Set the seconds, according to universal time (from 0-59) setyear() todatestring() togmtstring() tolocaledatestring() tolocaletimestring() tolocalestring() tostring() totimestring() toutcstring() UTC() valueof() Deprecated. Use the setfullyear() method instead Converts the date portion of a Date object into a readable string Deprecated. Use the toutcstring() method instead Returns the date portion of a Date object as a string, using locale conventions Returns the time portion of a Date object as a string, using locale conventions Converts a Date object to a string, using locale conventions Converts a Date object to a string Converts the time portion of a Date object to a string Converts a Date object to a string, according to universal time Returns the number of milliseconds in a date string since midnight of January, 970, according to universal time Returns the primitive value of a Date object What is an Array? An array is a special variable, which can hold more than one value, at a time Create an Array An array can be defined in three ways. The following code creates an Array object called mycars: : var mycars=new Array(); // regular array (add an optional integer mycars[0]="saab"; // argument to control array's size) mycars[]="volvo"; mycars[2]="bmw"; 2: var mycars=new Array("Saab","Volvo","BMW"); // condensed array 3: var mycars=["saab","volvo","bmw"]; // literal array Note: If you specify numbers or true/false values inside the array then the variable type will be Number or Boolean, instead of String. Access an Array You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0. The following code line: document.write(mycars[0]); will result in the following output: Saab 0

Array Object Methods Method Description concat() indexof() join() pop() push() reverse() shift() slice() sort() splice() tostring() unshift() valueof() Joins two or more arrays, and returns a copy of the joined arrays Joins all elements of an array into a string Removes the last element of an array, and returns that element Adds new elements to the end of an array, and returns the new length Reverses the order of the elements in an array Removes the first element of an array, and returns that element Selects a part of an array, and returns the new array Sorts the elements of an array Adds/Removes elements from an array Converts an array to a string, and returns the result Adds new elements to the beginning of an array, and returns the new length Returns the primitive value of an array Date Programes: <HTML> <BODY> <script> var mydate=new Date(); document.write("<h>"+mydate); </BODY></HTML> OutPut: Sat Feb 4 08:44:6 UTC+0530 202 <HTML> <BODY> <script> var mydate=new Date(); document.write("<h>"+mydate+"<br>"+mydate. getday()+"<br>"+mydate.getmonth()+"<br>"+my Date.getYear()+"<br>"+myDate.getHours()+"<br> "+mydate.getseconds()+"<br>"+mydate.gettime( )); </BODY> </HTML> OutPutL:Sat Feb 4 08:48:3 UTC+0530 202 6 202 8 3 3283258840

2 Mathematical Object Programs: <HTML> <BODY> <HR> <H>Math.abs()</H> document.write(math.abs(7.25) + "<br />"); document.write(math.abs(-7.25) + "<br />"); document.write(math.abs(null) + "<br />"); document.write(math.abs("hello") + "<br />"); document.write(math.abs(7.25-0)); <HR><H>Math.ceil</H> document.write(math.ceil(0.60) + "<br />"); document.write(math.ceil(0.40) + "<br />"); document.write(math.ceil(5) + "<br />"); document.write(math.ceil(5.) + "<br />"); document.write(math.ceil(-5.) + "<br />"); document.write(math.ceil(-5.9)); <HR><H>Math.floor</H> document.write(math.floor(0.60) + "<br />"); document.write(math.floor(0.40) + "<br />"); document.write(math.floor(5) + "<br />"); document.write(math.floor(5.) + "<br />"); document.write(math.floor(-5.) + "<br />"); document.write(math.floor(-5.9)); <HR><H>Math.sqrt</H> document.write(math.sqrt(0) + "<br />"); document.write(math.sqrt() + "<br />"); document.write(math.sqrt(9) + "<br />"); document.write(math.sqrt(0.64) + "<br />"); document.write(math.sqrt(-9)); <HR><H>Math.pow</H> document.write(math.pow(0,0) + "<br />"); document.write(math.pow(0,) + "<br />"); document.write(math.pow(,) + "<br />"); document.write(math.pow(,0) + "<br />"); document.write(math.pow(7,2) + "<br />"); document.write(math.pow(-7,2) + "<br />"); document.write(math.pow(2,4)); <HR><H>Math.round</H> document.write(math.round(0.60) + "<br />"); document.write(math.round(0.50) + "<br />"); document.write(math.round(0.49) + "<br />"); document.write(math.round(-4.40) + "<br />"); document.write(math.round(-4.60)); </BODY> </HTML> OutPut: Math.abs() 7.25 7.25 0 NaN 2.75 Math.ceil 5 6-5 -5 Math.floor 0 0 5 5-6 -6 Math.sqrt 0 3 0.8 NaN Math.pow 0 49 49 6 Math.round 0-4 -5