Chapter 4:- JavaScript. Compiled By:- Sanjay Patel Assistant Professor, SVBIT.

Size: px
Start display at page:

Download "Chapter 4:- JavaScript. Compiled By:- Sanjay Patel Assistant Professor, SVBIT."

Transcription

1 Chapter 4:- JavaScript Compiled By:- Assistant Professor, SVBIT.

2 Introduction JavaScript is a scripting language. A JavaScript consists of lines of executable computer code. A JavaScript is usually embedded directly into HTML pages. JavaScript was designed to add interactivity to HTML pages. JavaScript is free. Everyone can use JavaScript without a license. A scripting language is a lightweight programming language.

3 Client Side Server Side The client side scripting is a class of scripting language that are used on the client machine in the user s web browser. The client side scripting allows to change the content of the web page depending upon the user input. For example:- on clicking the button some message should be displayed. JavaScript is about "programming" the behavior of a browser. This is called client-side scripting (or browser scripting). Server-side scripting is about "programming" the behavior of the server (ASP/PHP/JSP).

4 Difference between Java and Java Script Java Requires the JDK to create the applet Requires a Java virtual machine to run the applet. Applet files are distinct from the XHTML code. Source code is hidden from the user. Programs must be saved as separate files and compiled before they can be run. Programs run on the server side. Java Script Requires a text editor Required a browser that can interpret JavaScript code JavaScript can be placed within HTML and XHTML. Source code is made accessible to the user Programs cannot write content to the hard disk. Programs run on the client side.

5 More Differences Java Java is a programming Language Java is a Object Oriented programming Language Java is strongly typed language and the type checking is done at compile time Object in java are static. That means the number of data members and method are fixed at compile time. Java Script Java script is a scripting Language Java Script is not a object oriented programming Language. It is object model is far different than a typical object oriented programming language such as C++ or Java. In Java Script variables need not be declared before their use. Checking the compatibility of type can be done dynamically. In JavaScript the objects are dynamic. That means we can change the total data members and method of an object during execution.

6 Advantages of JavaScript JavaScript is executed on the client side This means that the code is executed on the user's processor instead of the web server thus saving bandwidth and strain on the web server. JavaScript is a relatively easy language The JavaScript language is relatively easy to learn and comprises of syntax that is close to English.

7 Cont d.. JavaScript is relatively fast to the end user As the code is executed on the user's computer, results and processing is completed almost instantly depending on the task (tasks in JavaScript on web pages are usually simple so as to prevent being a memory hog) as it does not need to be processed in the site's web server and sent back to the user consuming local as well as server bandwidth.

8 Cont d.. Versatility JavaScript plays nicely with other languages and can be used in a huge variety of applications. Unlike PHP or SSI scripts, JavaScript can be inserted into any web page regardless of the file extension. JavaScript can also be used inside scripts written in other languages such as Perl and PHP.

9 Disadvantages Security Because the code executes on the users computer, in some cases it can be exploited for malicious purposes. This is one reason some people choose to disable JavaScript. Reliance on End User JavaScript is sometimes interpreted differently by different browsers. Whereas server-side scripts will always produce the same output, client-side scripts can be a little unpredictable. Don't be overly concerned by this though - as long as you test your script.

10 Java script Syntax Unlike HTML, JavaScript is case sensitive. Dot Syntax is used to combine terms. e.g., document.write("hello World") Certain characters and terms are reserved. JavaScript is simple text (ASCII).

11 Two ways to insert JS Code First way is to embedded it directly within the <script> and </script> tag pair The <script> tag notifies the browser that everything contained within is script and is to be interpreted by suitable interpreter. <script language= javascript > </script> Javascript code

12 Java Script in HTML Scripts in HTML must be inserted between <script> and </script> tags. Scripts can be put in the <body> and in the <head> section of an HTML page. The <script> and </script> tells where the JavaScript starts and ends.

13 Cont d.. <html> <body> <h1>my First Web Page</h1> <script language= JavaScript > document. write("<p>my First JavaScript</p>"); </script> </body> </html>

14 Second ways to insert JS Code Second way to insert JS code is to place and external source file and refer to it from an HTML file. This external source file generally has the extension.js. A source file contains only JavaScript statements without any script tag or other HTML tags <script language= javascript src= source.js > </script> Javascript code

15 Using the <script> Tag To embed a client-side script in a Web page, use the element: <script type= text/javascript > script commands and comments </script> To access an external script, use: <script src= url type= text/javascript > script commands and comments </script>

16 First JavaScript Program

17 Adding Comment

18 Example

19 Output

20 Methods Methods are actions applied to particular objects. Methods are what objects can do. e.g., document.write( Hello World") document is the object. write is the method.

21 Properties Properties are object attributes. Object properties are defined by using the object's name, a period, and the property name. e.g., background color is expressed by: document.bgcolor. document is the object. bgcolor is the property.

22 Basic Programming Technique Java scrip offers the very same programming capabilities found in most programming languages. Creating variables, constants, programming constructs, user defined functions and so on. These are the techniques that makes the java script the exciting programming language that extends the functionality of HTML and makes web pages interactive

23 Basic Programming Technique The <head> </head> tag make an ideal place to create JavaScript variables and constants and so on. This is because the head of an HTML document is always processed before the body. By using this technique the interpreter will always create functions, constants of structure before using them.

24 Basic Programming Technique It is important because any attempt to use a variable or any object before it is defined, results in an error. Variable name can begin with upper case or lowercase or underscore character or dollar sign character. The remaining characters can consist of letters, or underscore or digits. Variable names are case sensitive.

25 Point to be Remember The dollar sign ($) character is reserved for machine generated code and should not be used in scripts.

26 Data Types There are following types used in Java Script String Number Boolean Null & Undefined. Object Array

27 Variable Variables contain values and use the equal sign to specify their value. Variables are created by declaration using the var command with or without an initial value state. e.g. var month; e.g. var month = April ;

28 Which one is legal? My_variable $my_variable 1my_example My_variable_example ++my_variable %my_variable #my_variable ~my_variable myvariableexample Legal Illegal

29 Keyword

30 Local Variable Local variables are declared with in a function. Syntax:- var name_of_variable=value; The keyword var specifies the variable is a local variable and visible within the scope in which it is declared var total=0 //number var message= Hello ; var found=false; //string //boolean

31 Strings A string is a variable which stores a series of characters like MCA Dept.". A string can be any text inside quotes. You can use simple or double quotes: var carname="volvo XC60"; var carname='volvo XC60';

32 Cont d.. You can use quotes inside a string, as long as they don't match the quotes surrounding the string. var answer="it's alright"; var answer="he is called 'Johnny'"; var answer='he is called "Johnny"';

33 Concatenation The + operator can also be used to add string variables or text values together. txt1="what a very"; txt2="nice day"; txt3=txt1+txt2; What a verynice day

34 Number JavaScript has only one type of numbers. Numbers can be written with, or without decimals. var x1=34.00; var x2=34; //Written with decimals //Written without decimals Extra large or extra small numbers can be written with scientific (exponential) notation: var y=123e5; // var z=123e-5; //

35 Boolean Booleans can only have two values: true or false. var x=true var y=false Booleans are often used in conditional testing.

36 Null Undefined is the value of a variable with no value. Variables can be emptied by setting the value to null; cars=null; person=null;

37 Object An object is delimited by curly braces. Inside the braces the object's properties are defined as name and value pairs (name : value). The properties are separated by commas: var person={firstname:"john", lastname:"doe, id:5566};

38 Object The object (person) in the example Below has 3 properties: firstname, lastname, and id. Spaces and line breaks are not important. Your declaration can span multiple lines: var person={ firstname : "John, lastname : "Doe, id : 5566 };

39 Operator Arithmetic Assignment Concatenation Comparison Logical Conditional

40 Arithmetic Arithmetic operators are used to perform arithmetic between variables and/or values. Operator Name Description Example + Addition Adds the operands Subtraction Subtracts the right operand from the left operand 5-3 * Multiplication Multiplies the operands 3 * 5 / Division Divides the left operand by the right operand 30 / 5 % Modulus Calculates the remainder 20 % 5

41 Arithmetic Operator Given that y=5, the table below explains the arithmetic operators:

42 Example Of operator

43 Output

44 Cont d.. Example Result var result = 2 + 3; 5 result = Hello + World ; Hello World result = 2 + MB ; 2MB result = P + 4 ; P4 result = Y K ; Y2K result = K ; (2+3) + K = 5K result = K ; ( K +2) +3 = K23 result = Age: <br> ; Age: 32 <br>

45 Assignment Assignment operators are used to assign values to JavaScript variables. Given that x=10 and y=5, the table below explains the assignment operators:

46 Comparison 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:

47 Comparison Operator Name Description Example == Equal Perform type conversion before checking the equality 5 == 5 === Strictly equal No type conversion before testing 5 === 5!= Not equal true when both operands are not equal 4!= 2!== Strictly not equal No type conversion before testing nonequality 5!== 5 > Greater than true if left operand is greater than right operand 2 > 5 < Less than true if left operand is less than right operand 3 < 5 >= Greater than or equal <= Less than or equal true if left operand is greater than or equal to the right operand true if left operand is less than or equal to the right operand 5 >= 2 5 <= 2

48 Operator Precedence Operators having higher precedence are evaluated before operators having lower precedence. Arithmetic operator precedence Precedence Operators Lowest +, - *, /,% Highest ++, - -

49 Example

50 Output

51 Logical Logical operators are used to determine the logic between variables or values. Operator Name Description Example && Logical and Evaluate to true when both operands are true Logical or Evaluate to true when either operand is true! Logical not Evaluate to true when the operand is false 3>2 && 5<2 3>1 2>5 5!= 3

52 Cont d.. Given that x=6 and y=3, the table below explains the logical operators:

53 Conditional Statement JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. Syntax variablename=(condition)?value1:value2; Example voteable=(age<18)?"too young":"old enough";

54 Conditional Statements if if...else if...else if...else switch

55 Conditional Statements Very often when you write code, you want toperform different actions for different decisions. You can use conditional statements in your code to do this. 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

56 If Statements if statement:- Use the if statement to execute some code only if a specified condition is true. Syntax :- if (condition) Example:- { code to be executed if condition is true } if (time<20) { x="good day"; }

57 If.else statement if...else statement :- Use the if...else statement to execute some code if a condition is true and another code if the condition is not true. Syntax:- else if (condition) { code to be executed if condition is true } { code to not be executed if condition is true }

58 Example if (time<20) { } else { } x="good day"; x="good evening";

59 Example

60 Output

61 Example

62 Output

63 Switch case Statement Syntax:- switch(n) { case 1: execute code block 1 break; case 2: execute code block 2 break; default: code to be executed if n is different from case 1 and 2 }

64 Example

65 Output

66 Looping Statements While Loop Do while Loop For Loop

67 Syntax

68 Example

69 Output

70 Example

71 Output

72 Cont d..

73 For loop

74 For loop

75 Cont d..

76 Mathematical Functions abs() ceil() random() pow() floor() sqrt()

77 abs() Return the absolute value of a number: Syntax:- The output of the code above will be: NaN 5

78 ceil() Round a number upward to it's nearest integer: Syntax:- The output of the code above will be:

79 random() The random() method returns a random number between 0 and 1. Syntax:-

80 pow() The pow() method returns the value of x to the power of y (x y ). Syntax:- The output of the code above will be:

81 floor() The floor() method rounds a number DOWNWARDS to the nearest integer, and returns the result. If the passed argument is an integer, the value will not be rounded. Syntax:- Output:

82 sqrt() The sqrt() method returns the square root of a number. Syntax:- Output: Nan

83 Example of more Math Function Method Description Example abs( x ) absolute value of x abs( 7.2 ) is 7.2 abs( 0.0 ) is 0.0 abs( -5.6 ) is 5.6 ceil( x ) rounds x to the smallest integer not less than x ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0 cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0 (x in radians) exp( x ) exponential method ex exp( 1.0 ) is exp( 2.0 ) is floor( x ) rounds x to the largest floor( 9.2 ) is 9.0 integer not greater than x floor( -9.8 ) is log( x ) natural logarithm of x (base e) log( ) is 1.0 log( ) is 2.0 max( x, y ) larger value of x and y max( 2.3, 12.7 ) is 12.7 max( -2.3, ) is -2.3

84 Cont d.. min( x, y ) smaller value of x min( 2.3, 12.7 ) is 2.3 and y min( -2.3, ) is pow( x, y ) x raised to power y pow( 2.0, 7.0 ) is (xy) pow( 9.0,.5 ) is 3.0 round( x ) rounds x to the closest integer round( 9.75 ) is 10 round( 9.25 ) is 9 sin( x ) trigonometric sine of sin( 0.0 ) is 0.0 x (x in radians) sqrt( x ) square root of x sqrt( ) is 30.0 sqrt( 9.0 ) is 3.0 tan( x ) trigonometric tangent tan( 0.0 ) is 0.0 of x (x in radians) Fig Math object methods.

85 String Functions big() blink() bold() italics() charat() tolowercase() touppercase() substring()

86 big() The big() method is used to display a string in a big font. This method returns the string embedded in the <big> tag, like this: Syntax:- The output of the code above will be: hello world!

87 blink() The blink() method is used to display a blinking string. This method returns the string embedded in the <blink> tag, like this: Syntax:- The blink() method only works in Firefox and Opera.It is not supported in Internet Explorer, Chrome, or Safari.

88 bold() The bold() method is used to display a string in bold. This method returns the string embedded in the <b> tag, like this: Syntax:- The output of the code above will be:-hello world!

89 Date Functions getdate() setdate() gethours() sethours() gettime() settime()

90 getdate() The getdate() method returns the day of the month (from 1 to 31) for the specified date. Syntax:- The output of the code above will be: 21

91 SetDate() The setdate() method sets the day of the month to the date object. Syntax:- The output of the code above will be: Fri Jul :15:00 GMT+0530

92 SetDate() An integer representing the day of a month. Expected values are 1-31, but other values are allowed: 0 will result in the last day of the previous month -1 will result in the day before the last day of the previous month If the month has 31 days.32 will result in the first day of the next month If the month has 30 days.32 will result in the second day of the next month

93 gettime() The gettime() method returns the number of milliseconds between midnight of January 1, 1970 and the specified date. Syntax:-

94 settime() The settime() method sets a date and time by adding or subtracting a specified number of milliseconds to/from midnight January 1, Syntax:-

95 gethours() The gethours() method returns the hour (from 0 to 23) of the specified date and time. Syntax:- The output of the code above will be: 1

96 sethours() The gethours() method returns the hour (from 0 to 23) of the specified date and time. Syntax:- The output of the code above will be: Fri Nov :35:01 GMT+0530

97 Array An array literal is written using square brackets with array elements separated using by commas(,).. Examples var array_name=[element 0, element 2..element n ]; var number=[1,2,3,4]; How to access an element? Same as other language Example var alpha=[ a, b, c, d, e ]; var colors=[ red, green, blue ]; Name_of_an_array[index/subscript] number[0],number[2] colors[0]

98 Array The following code creates an Array called cars: var cars=new Array(); cars[0]="saab"; cars[1]="volvo"; cars[2]="bmw"; It can also be declared as: var cars=new Array("Saab","Volvo","BMW"); And even as: var cars=["saab","volvo","bmw"];

99 Heterogeneous Array

100 Array Example

101 Output

102 Example

103 Output

104 Array concat

105 Output

106 Array Push The push() method adds new items to the end of an array, and returns the new length. Note: The new item(s) will be added at the end of the array. Note: This method changes the length of the array. var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits. Push("Kiwi ) Banana,Orange, Apple,Mango,Kiwi

107 Array Pop The pop() method removes the last element of an array, and returns that element. Note: This method changes the length of an array. var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.pop(); Banana,Orange,Apple

108 Array Join

109 Output

110 Array Shift The shift() method removes the first item of an array, and returns that item. Note: This method changes the length of an array! Tip: To remove the last item of an array, use the pop() method. var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits. Shift() Orange, Apple,Mango

111 Array Unshift The unshift() method adds new items to the beginning of an array, and returns the new length. Note: This method changes the length of an array. Tip: To add new items at the end of an array, use the push() method var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.unshift("lemon","pineapple"); Lemon,Pineapple,Banana, Orange,Apple,Mango

112 Slice() The slice() method returns the selected elements in an array, as a new array object. The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument. Syntax:- array.slice(start, end) var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; var citrus = fruits. slice(1,3); Orange,Lemon

113 Syntax Syntax:- array.slice(start, end) Parameter start end Description Required. An integer that specifies where to start the selection (The first element has an index of 0). Use negative numbers to select from the end of an array Optional. An integer that specifies where to end the selection. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array

114 Example

115 Output

116 splice() The splice() method adds/removes items to/from an array, and returns the removed item(s). Syntax:- array.splice(index,howmany,item1,...,itemx) Parameter index howmany item1,..., itemx Description Required. An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array Required. The number of items to be removed. If set to 0, no items will be removed Optional. The new item(s) to be added to the array

117 Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(2,0,"lemon","kiwi"); var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(2,2,"lemon","kiwi"); var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(2,1,"lemon","kiwi"); Banana,Orange,Lemon,Kiwi,Apple,Mango Banana,Orange,Lemon, Kiwi Banana,Orange,Lemon, Kiwi,Mango

118 Built in Objects Date String Math

119 String Complete Example

120 Output

121 Date constructor Date() Constructor Description This creates a Date object with the current date and time of the browser s PC Date( Month dd, yyyy hh:mm:ss ) This creates a Date object, with the date specified by a date string in the format Month dd, yyyy hh:mm:ss Date( Month dd, yyyy ) Date(yy, mm, dd hh, mm, ss) Date(yy, mm, dd) This creates a Date object, with the date specified by a date string in the format Month dd, yyyy This creates a Date object with the specified date and time This creates a Date object with the specified date

122 Full Date Example Demo

123 Output

124 Mathematical Functions abs() ceil() random() pow() floor() sqrt()

125 Math() Object Example

126 Output

127 Built in Function eval() parseint() parsefloat() isfinite()

128 eval() The eval() function evaluates or executes an argument. If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements. Syntax The eval() function is supported in all major browsers.

129 Example The output of the code above will be:

130 parseint() The parseint() function parses a string and returns an integer. Syntax:- The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number

131 parseint() If the radix parameter is omitted, JavaScript assumes the following: If the string begins with "0x", the radix is 16 (hexadecimal) If the string begins with "0", the radix is 8 (octal). This feature is deprecated If the string begins with any other value, the radix is 10 (decimal)

132 parseint() Only the first number in the string is returned! Leading and trailing spaces are allowed. If the first character cannot be converted to a number, parseint() returns NaN.

133 Example

134 Output

135 parsefloat() The parsefloat() function parses a string and returns a floating point number. This function determines if the first character in the specified string is a number. If it is, it parses the string until it reaches the end of the number, and returns the number as a number, not as a string.

136 Cont d.. Only the first number in the string is returned! Leading and trailing spaces are allowed. If the first character cannot be converted to a number, parsefloat() returns NaN.

137 Example

138 Output

139 isfinite() The isfinite() function determines whether a number is a finite, legal number. Syntax:- This function returns false if the value is +infinity, - infinity, or NaN.

140 Example

141 Output

142 User-defined Functions A function is a block of code that will be executed when "someone" calls it: A function is written as a code block (inside curly { } braces), preceded by the function keyword:

143 Cont d..

144 Function Example

145 Factorial with Function

146 JavaScript Pop boxes JavaScript has three kind of popup boxes. Alert box. Confirm box. Prompt box.

147 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. Syntax:- window.alert("sometext");

148 Syntax There are many ways to add a handler to an event. The straightforward way is to specify it in the tag as follows <input type= button value= clickme onclick= alert( You clicked Me ); event Event Handler

149 Example <html><head> <script> function myfunction() { alert("i am an alert box!"); } </script> </head><body> <input type="button" onclick="myfunction()" value="show alert box > </body></html>

150 Output

151 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. Syntax:- window.confirm("sometext");

152 <html><body> <p>click the button to display a confirm box.</p> <button onclick="myfunction()">try it</button> <p id="demo"></p> <script> function myfunction() { var x; var r=confirm("press a button!"); if (r==true) { x="you pressed OK!"; } else { x="you pressed Cancel!"; } document.getelementbyid("demo").innerhtml=x; } </script></body></html>

153 Output

154 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. Syntax:- window.prompt("sometext","defaultvalue");

155 <html><body> <p>click the button to demonstrate the prompt box.</p> <button onclick="myfunction()">try it</button> <p id="demo"></p> <script> function myfunction() { var x; var name=prompt("please enter your name","harry Potter"); if (name!=null) { x="hello " + name + "! How are you today?"; document.getelementbyid("demo").innerhtml=x; } } </script></body></html>

156 Output

157 getelementbyid() The getelementbyid() method accesses the first element with the specified id. This is the most powerful and the most complex method (but don't worry, it's really easy!).

158 Syntax Syntax:- document.getelementbyid("id") Where id is required. Everything on a web page resides in a box. A paragraph (<P>) is a box. When you mark something as bold you create a little box around that text that will contain bold text. You can give each and every box in HTML a unique identifier (an ID), and Javascript can find boxes you have labeled and let you manipulate them. Well enough, check out the code!

159 Code <html><head></head> <body> <div id='feedback'></div> <script type='text/javascript'> document.getelementbyid('feedback').innerhtml= 'Hello World!'; </script> </body></html> Output:- Hello World!

160 Description Here we defined a division <div> and named it "feedback". That HTML has a name now, it is unique and that means we can use JavaScript to find that block, and modify it. We do exactly this in the script below the division! The left part of the statement says on this web page (document) find a block we've named "feedback" ( getelementbyid('feedback') ), and change its HTML (innerhtml) to be 'Hello World!'. We can change the contents of 'feedback' at any time, even after the page has finished loading (which document.writeln can't do), and without annoying the user with a bunch of popup alert boxes (which alert can't do!).

161 innerhtml and getelementbyid

162 Output

163 Can you find out the Problem?

164 Output

165 Solution is:-getelementsbytagname() Method

166 Output

167 Input (One Click To Rule Them All) Input, of course, is a little more complicated. For now we'll just reduce it to a bare click of the mouse. If everything in HTML is a box and every box can be given a name, then every box can be given an event as well and one of those events we can look for is "onclick". Lets revisit our last example...

168 Mouse click example <html><head></head> <body> <div id='feedback' onclick='goodbye()'>users without Javascript see this.</div> <script type='text/javascript > document.getelementbyid('feedback').innerhtml='hello World! ; function goodbye() { document.getelementbyid('feedback').innerhtml='goodbye World!'; } </script></body></html>

169 Output

170 Two Concept has been done first we added an "onclick" event to our feedback division which tells it to execute a function called goodbye() when the user clicks on the division. A function is nothing more than a named block of code. In this example goodbye does the exact same thing as our first hello world example, it's just named and inserts 'Goodbye World!' instead of 'Hello World!'.

171 Cont d.. Second new concept in this example is that we provided some text for people without Javascript to see. As the page loads it will place "Users without Javascript will see this." in the division. If the browser has Javascript, and it's enabled then that text will be immediately overwritten by the first line in the script which looks up the division and inserts "Hello World!", overwriting our initial message. This happens so fast that the process is invisible to the user, they see only the result, not the process. The goodbye() function is not executed until it's explicitly called and that only happens when the user clicks on the division.

172 Input (User Input) Clicks are powerful and easy and you can add an onclick event to pretty much any HTML element, But sometimes you need to be able to ask for input from the user and process it. For that you'll need a basic form element and a button

173 HTML Forms and JavaScript JavaScript is very good at processing user input in the web browser HTML <form> elements receive input Forms and form elements have unique names Each unique element can be identified Uses JavaScript Document Object Model (DOM)

174 Naming Form Elements in HTML <form name="addressform"> Name: <input name="yourname"><br /> Phone: <input name="phone"><br /> <input name=" "><br /> </form>

175 Forms and JavaScript document.formname.elementname.value Thus: document.addressform.yourname.value document.addressform.phone.value document.addressform. .value

176 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>

177 Example <html><head></head> <body> <input id='userinput' size=60> <button onclick='usersubmit()'>submit</button><br> <div id='result'></div> <script type='text/javascript > function usersubmit() { var UI=document.getElementById('userInput').value; document.getelementbyid('result').innerhtml='you typed: '+UI; } </script></script></body></html>

178 Output

179 Explanation Here we create an input field and give it a name of userinput. Then we create a HTML button with an onclick event that will call the function usersubmit(). These are all standard HTML form elements but they're not bound by a <form> tag since we're not going to be submitting this information to a server. Instead, when the user clicks the submit button, the onclick event will call the usersubmit() function

180 Cont d.. we create a variable called UI which looks up the input field userinput. This lookup is exactly the same as when we looked up our feedback division in the previous example. Since the input field has data, we ask for its value and place that value in our UI variable. The next line looks up the result division and puts our output there. In this case the output will be "You Typed: " followed by whatever the user had typed into the input field.

181 onkeyup() event (Without Button) <html><head></head><body> <input id='userinput' onkeyup="usersubmit()" size=60><br> <div id='result'></div> <script type='text/javascript > function usersubmit() { var UI=document.getElementById('userInput').value; document.getelementbyid('result').innerhtml='you typed: '+UI; } </script></body></html>

182 Output

183 Password Validation Criteria

184 Password Validation Example <script type="text/javascript > function confirmpass() { var sa = document.getelementbyid("pass").value; var confpass = document.getelementbyid("c_pass").value; if(sa==null) { alert("please enter"); pass.focus(); return false; } else if(sa!= confpass) { alert("re-enetr!"); pass.focus(); pass.select(); return false; } else { alert("enjoy"); return true; } }

185 Validation

186 Regular Expression Brackets are used to find a range of characters. Expression Description [abc] Find any character between the brackets [^abc] Find any character not between the brackets [0-9] Find any digit from 0 to 9 [A-Z] Find any character from uppercase A to uppercase Z [a-z] Find any character from lowercase a to lowercase z [A-z] Find any character from uppercase A to lowercase z [adgk] Find any character in the given set (red blue green) Find any of the alternatives specified

187 Regular Expression Metacharacters are characters with a special meaning. Metacharacter Description. Find a single character, except newline or line terminator \w Find a word character \W Find a non-word character \d Find a digit \D Find a non-digit character \s Find a whitespace character \S Find a non-whitespace character \b Find a match at the beginning/end of a word \B Find a match not at the beginning/end of a word \0 Find a NUL character

188 Event The purpose of using JavaScript is to add interactivity in web pages. i.e. we need to respond to user actions. When users performs some tasks on a web page are called events. For example, when user click on a button on a web page, a click event occurs. The button is called the source of the event. Other events such as, hyperlink( mouse over event), submitting a form(submit event), a keystroke (key press event)

189 Event Handlers JavaScript identifies an event and takes an action by executing piece of code. The procedure of taking action is called event handling The specific JavaScript code that take the action is called event handler. An event handler may be any valid JavaScript statements. In JavaScript, the handler of provided as a function. an event is usually

190 Window object Method Method alert() blur() close() confirm() createpopup() focus() moveby() moveto() open() print() prompt() resizeby() resizeto() scrollby() scrollto() setinterval() settimeout() Description Displays an alert box with a message and an OK button Removes focus from the current window Closes the current window Displays a dialog box with a message and an OK and a Cancel button Creates a pop-up window Sets focus to the current window Moves a window relative to its current position Moves a window to the specified position Opens a new browser window Prints the content of the current window Displays a dialog box that prompts the visitor for input Resizes the window by the specified pixels Resizes the window to the specified width and height` Scrolls the content by the specified number of pixels Scrolls the content to the specified coordinates Calls a function or evaluates an expression at specified intervals (in milliseconds) Calls a function or evaluates an expression after a specified number of milliseconds

191 Example

192 Output

193

194

195 Example

196

197 Prompt Box Demo

198 Output

199 Java Script is an Event Driven Language As you can tell from the input examples, Javascript is an event driven language which means your scripts react to events you set up. Your code isn't running all the time, it simply waits until an event starts something up! Going into all the JavaScript events is beyond the scope of this document but here's a short-list of common events to get you started.

200

201 Location Object The JavaScript window object has a property location (access by window.location or location), which encapsulates the current URL that is displayed in the visitor s browser. This object has several useful properties and methods that may be used to inspect or changed different fields of a URL or even change the entire URL.

202 Example

203 Another Location Object Example

204 History Object The JavaScript window object has another important property history (accessed as window.history or history ), which stores information about URLs already visited from the browser s window. Property length back() forward() go() Method Description Returns the number of URLs in the history list Description Loads the previous URL in the history list Loads the next URL in the history list Loads a specific URL from the history list

205 Example

206 HTML DOM The HTML DOM defines a standard way for accessing and manipulating HTML documents. The DOM presents an HTML document as a treestructure. In Simple words, With the HTML DOM, JavaScript can access all the elements of an HTML document. When a web page is loaded, the browser creates a Document Object Model of the page. The HTML DOM model is constructed as a tree of Objects:

207 What is DOM? Document object model is a set of platform independent and language-neutral application programming interface(api) which describes how to access and manipulate the information stored in XML,XHTML and javascript document DOM is a platform- and language-neutral interface that allow programs and scripts to dynamically access and manipulate the content, structure and style of documents.

208 HTML DOM Tree

209 DOM Node According to the DOM, everything in an HTML document is a node. The DOM says: The entire document is a document node Every HTML element is an element node The text in the HTML elements are text nodes Every HTML attribute is an attribute node Comments are comment nodes

210 Example The root node in the HTML above is <html>. All other nodes in the document are contained within <html>. The <html> node has two child nodes; <head> and <body>. The <head> node holds a <title> node. The <body> node holds a <h1> and <p> node.

211 Programming Interface In the DOM, HTML documents consist of a set of node objects. The nodes can be accessed with JavaScript or other programming languages Properties are often referred to as something that is (i.e. the name of a node). Methods are often referred to as something that is done (i.e. remove a node).

212 HTML DOM Properties x.innerhtml - the text value of x x.nodename - the name of x x.nodevalue - the value of x x.parentnode - the parent node of x x.childnodes - the child nodes of x x.attributes - the attributes nodes of x

213 HTML DOM Methods x.getelementbyid(id) - get the element with a specified id x.getelementsbytagname(name) - get all elements with a specified tag name x.appendchild(node) - insert a child node to x x.removechild(node) - remove a child node from x

214 The innerhtml Property The easiest way to get or modify the content of an element is by using the innerhtml property. innerhtml is not a part of the W3C DOM specification. However, it is supported by all major browsers. The innerhtml property is useful for returning or replacing the content of HTML elements (including <html> and <body>), it can also be used to view the source of a page that has been dynamically modified.

215 Example

216 Accessing Nodes We can access a node in three ways: By using the getelementbyid() method By using the getelementsbytagname() method By navigating the node tree, using the node relationships

217 JavaScript HTML DOM - Changing HTML <html><body> <p id="p1">hello World!</p> <script> document.getelementbyid("p1"). innerhtml="new text!"; </script> <p>the paragraph above was changed by a script.</p> </body></html> New text! The paragraph above was changed by a script

218 JavaScript HTML DOM - Changing CSS <html><body> <p id="p1">hello World!</p> <p id="p2">hello World!</p> <script> document.getelementbyid("p2").style.color="blue"; document.getelementbyid("p2").style.fontfamily="arial"; document.getelementbyid("p2").style.fontsize="larger"; </script> <p>the paragraph above was changed by a script.</p> </body></html>

219 Cont d.. Hello World! Hello World! The paragraph above was changed by a script.

220 DHTML DHTML is the combination of 3 browser technologies to render a dynamic browser experience HTML for content Cascading Style Sheets for general presentation Javascript to enable dynamic presentation Generally, DHTML refers to applications that allow a Web page to change dynamically without requiring information to be passed to/from a web server. More specifically, DHTML refers to the interaction of HTML, CSS and Scripting language (JavaScript). DHTML = HTML + CSS + JavaScript + DOM

221 Affect the DOM through HTML (content) Cascading Style Sheets (general presentation) Browser DOM Javascript (and other scripting languages) for most dynamic effects

222 Why comes DHTML? With Dynamic HTML the emphasis is on making the browser provide a richer viewing experience through effects like Animation Filters Transitions This is done by applying properties and methods of the Browser s Document Object Model (DOM) This is usually done through Javascript, but it can also be done by any scripting language supported by the browser, such as VB-Script

223 In simple Words. To make Web pages interactive. HTML pages have static nature. DHTML provides us with enhanced creative control so we can manipulate any page element at any time. It is the easiest way to make Web pages interactive. It doesn t increase server workload and require special software to support.

224 Difference Between HTML and DHTML HTML HTML is used to create static web pages DHTML DHTML is used to create Dynamic web pages The HTML consists of simple HTML tags DHTML is made up of HTML tags + CSS + Java Script The HTML does not allow to alter the text and graphics on the web page unless web page get changed Creation of HTML web pages is simplest but less interactive DHTML, you can alter the text and graphics of the web page and for that matter you need not have to change the entire web page. Creation of DHTML web pages is complex but more interactive

225 Change an HTML Element HTML DOM and JavaScript can change the inner content and attributes of HTML elements. The following example changes the background color of the <body> element:

226 Example

Princess Nourah bint Abdulrahman University. Computer Sciences Department

Princess Nourah bint Abdulrahman University. Computer Sciences Department Princess Nourah bint Abdulrahman University 1 And use http://www.w3schools.com/ JavaScript Objectives Introduction to JavaScript Objects Data Variables Operators Types Functions Events 4 Why Study JavaScript?

More information

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

What is Java Script? Writing to The HTML Document. What Can JavaScript do? CMPT 165: Java Script What is Java Script? CMPT 165: Java Script Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University November 7, 2011 JavaScript was designed to add interactivity to HTML pages

More information

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

CITS1231 Web Technologies. JavaScript Math, String, Array, Number, Debugging CITS1231 Web Technologies JavaScript Math, String, Array, Number, Debugging Last Lecture Introduction to JavaScript Variables Operators Conditional Statements Program Loops Popup Boxes Functions 3 This

More information

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

PES DEGREE COLLEGE BANGALORE SOUTH CAMPUS 1 K.M. before Electronic City, Bangalore WEB PROGRAMMING Solution Set II PES DEGREE COLLEGE BANGALORE SOUTH CAMPUS 1 K.M. before Electronic City, Bangalore 560 100 WEB PROGRAMMING Solution Set II Section A 1. This function evaluates a string as javascript statement or expression

More information

Client-Side Web Technologies. JavaScript Part I

Client-Side Web Technologies. JavaScript Part I Client-Side Web Technologies JavaScript Part I JavaScript First appeared in 1996 in Netscape Navigator Main purpose was to handle input validation that was currently being done server-side Now a powerful

More information

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

By the end of this section of the practical, the students should be able to: By the end of this section of the practical, the students should be able to: Write JavaScript to generate HTML Create simple scripts which include input and output statements, arithmetic, relational and

More information

Such JavaScript Very Wow

Such JavaScript Very Wow Such JavaScript Very Wow Lecture 9 CGS 3066 Fall 2016 October 20, 2016 JavaScript Numbers JavaScript numbers can be written with, or without decimals. Extra large or extra small numbers can be written

More information

JavaScript CS 4640 Programming Languages for Web Applications

JavaScript CS 4640 Programming Languages for Web Applications JavaScript CS 4640 Programming Languages for Web Applications 1 How HTML, CSS, and JS Fit Together {css} javascript() Content layer The HTML gives the page structure and adds semantics Presentation

More information

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

710 Index Attributes, 127 action attribute, 263 assigning, bottom attribute, domain name attribute, 481 expiration date attribute, 480 8 INDEX Symbols = (assignment operator), 56 \ (backslash), 33 \b (backspace), 33 \" (double quotation mark), 32 \e (escape), 33 \f (form feed), 33

More information

CGS 3066: Spring 2015 JavaScript Reference

CGS 3066: Spring 2015 JavaScript Reference CGS 3066: Spring 2015 JavaScript Reference Can also be used as a study guide. Only covers topics discussed in class. 1 Introduction JavaScript is a scripting language produced by Netscape for use within

More information

JavaScript CS 4640 Programming Languages for Web Applications

JavaScript CS 4640 Programming Languages for Web Applications JavaScript CS 4640 Programming Languages for Web Applications 1 How HTML, CSS, and JS Fit Together {css} javascript() Content layer The HTML gives the page structure and adds semantics Presentation

More information

COMS 469: Interactive Media II

COMS 469: Interactive Media II COMS 469: Interactive Media II Agenda Review Ch. 5: JavaScript An Object-Based Language Ch. 6: Programming the Browser Review Data Types & Variables Data Types Numeric String Boolean Variables Declaring

More information

CSC Web Programming. Introduction to JavaScript

CSC Web Programming. Introduction to JavaScript CSC 242 - Web Programming Introduction to JavaScript JavaScript JavaScript is a client-side scripting language the code is executed by the web browser JavaScript is an embedded language it relies on its

More information

The first sample. What is JavaScript?

The first sample. What is JavaScript? Java Script Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Firefox, Chrome, Opera, and Safari. In this lecture

More information

COMS W3101: SCRIPTING LANGUAGES: JAVASCRIPT (FALL 2018)

COMS W3101: SCRIPTING LANGUAGES: JAVASCRIPT (FALL 2018) COMS W3101: SCRIPTING LANGUAGES: JAVASCRIPT (FALL 2018) RAMANA ISUKAPALLI RAMANA@CS.COLUMBIA.EDU 1 LECTURE-1 Course overview See http://www.cs.columbia.edu/~ramana Overview of HTML Formatting, headings,

More information

(Refer Slide Time: 01:40)

(Refer Slide Time: 01:40) Internet Technology Prof. Indranil Sengupta Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture No #25 Javascript Part I Today will be talking about a language

More information

JavaScript Basics. The Big Picture

JavaScript Basics. The Big Picture JavaScript Basics At this point, you should have reached a certain comfort level with typing and running JavaScript code assuming, of course, that someone has already written it for you This handout aims

More information

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

CSS The web browser uses its own resources, and eases the burden on the server. It has fewer features than server side scripting. What is JavaScript? HTML and CSS concentrate on a static rendering of a page; things do not change on the page over time, or because of events. To do these things, we use scripting languages, which allow

More information

Introduction to JavaScript

Introduction to JavaScript 127 Lesson 14 Introduction to JavaScript Aim Objectives : To provide an introduction about JavaScript : To give an idea about, What is JavaScript? How to create a simple JavaScript? More about Java Script

More information

3 The Building Blocks: Data Types, Literals, and Variables

3 The Building Blocks: Data Types, Literals, and Variables chapter 3 The Building Blocks: Data Types, Literals, and Variables 3.1 Data Types A program can do many things, including calculations, sorting names, preparing phone lists, displaying images, validating

More information

<form>. input elements. </form>

<form>. input elements. </form> CS 183 4/8/2010 A form is an area that can contain form elements. Form elements are elements that allow the user to enter information (like text fields, text area fields, drop-down menus, radio buttons,

More information

Web Programming/Scripting: JavaScript

Web Programming/Scripting: JavaScript CS 312 Internet Concepts Web Programming/Scripting: JavaScript Dr. Michele Weigle Department of Computer Science Old Dominion University mweigle@cs.odu.edu http://www.cs.odu.edu/~mweigle/cs312-f11/ 1 Outline!

More information

JavaScript Introduction

JavaScript Introduction JavaScript Introduction JavaScript: Writing Into HTML Output document.write("this is a heading"); document.write("this is a paragraph"); JavaScript: Reacting to Events

More information

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) Technology & Information Management Instructor: Michael Kremer, Ph.D. Class 1 Professional Program: Data Administration and Management JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) WHO

More information

JavaScript: The Basics

JavaScript: The Basics JavaScript: The Basics CISC 282 October 4, 2017 JavaScript A programming language "Lightweight" and versatile Not universally respected Appreciated in the web domain Adds programmatic functionality to

More information

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

A.A. 2008/09. Why introduce JavaScript. G. Cecchetti Internet Software Technologies Internet t Software Technologies JavaScript part one IMCNE A.A. 2008/09 Gabriele Cecchetti Why introduce JavaScript To add dynamicity and interactivity to HTML pages 2 What s a script It s a little interpreted

More information

Javascript. UNIVERSITY OF MASSACHUSETTS AMHERST CMPSCI 120 Fall 2010

Javascript. UNIVERSITY OF MASSACHUSETTS AMHERST CMPSCI 120 Fall 2010 Lecture 14 Javascript Announcements Project #2 New website Exam#2 No. Class Date Subject and Handout(s) 17 11/4/10 Examination Review Practice Exam PDF 18 11/9/10 Search, Safety, Security Slides PDF UMass

More information

Chapter 2 Working with Data Types and Operators

Chapter 2 Working with Data Types and Operators JavaScript, Fourth Edition 2-1 Chapter 2 Working with Data Types and Operators At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

URLs and web servers. Server side basics. URLs and web servers (cont.) URLs and web servers (cont.) Usually when you type a URL in your browser:

URLs and web servers. Server side basics. URLs and web servers (cont.) URLs and web servers (cont.) Usually when you type a URL in your browser: URLs and web servers 2 1 Server side basics http://server/path/file Usually when you type a URL in your browser: Your computer looks up the server's IP address using DNS Your browser connects to that IP

More information

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

JavaScript. History. Adding JavaScript to a page. CS144: Web Applications JavaScript Started as a simple script in a Web page that is interpreted and run by the browser Supported by most modern browsers Allows dynamic update of a web page More generally, allows running an arbitrary

More information

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

JavaScript. History. Adding JavaScript to a page. CS144: Web Applications JavaScript Started as a simple script in a Web page that is interpreted and run by the browser Supported by most modern browsers Allows dynamic update of a web page More generally, allows running an arbitrary

More information

JME Language Reference Manual

JME Language Reference Manual JME Language Reference Manual 1 Introduction JME (pronounced jay+me) is a lightweight language that allows programmers to easily perform statistic computations on tabular data as part of data analysis.

More information

Then there are methods ; each method describes an action that can be done to (or with) the object.

Then there are methods ; each method describes an action that can be done to (or with) the object. When the browser loads a page, it stores it in an electronic form that programmers can then access through something known as an interface. The interface is a little like a predefined set of questions

More information

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

write vs. writeln Prompting as Page Loads Today s Goals CSCI 2910 Client/Server-Side Programming Intermediate File vs. HTML Output CSCI 2910 Client/Server-Side Programming Topic: JavaScript Part 2 Today s Goals Today s lecture will cover: More objects, properties, and methods of the DOM The Math object Introduction to form validation

More information

introjs.notebook March 02, 2014

introjs.notebook March 02, 2014 1 document.write() uses the write method to write on the document. It writes the literal Hello World! which is enclosed in quotes since it is a literal and then enclosed in the () of the write method.

More information

Variables and Typing

Variables and Typing Variables and Typing Christopher M. Harden Contents 1 The basic workflow 2 2 Variables 3 2.1 Declaring a variable........................ 3 2.2 Assigning to a variable...................... 4 2.3 Other

More information

COMS W3101: SCRIPTING LANGUAGES: JAVASCRIPT (FALL 2017)

COMS W3101: SCRIPTING LANGUAGES: JAVASCRIPT (FALL 2017) COMS W3101: SCRIPTING LANGUAGES: JAVASCRIPT (FALL 2017) RAMANA ISUKAPALLI RAMANA@CS.COLUMBIA.EDU 1 LECTURE-1 Course overview See http://www.cs.columbia.edu/~ramana Overview of HTML Formatting, headings,

More information

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

a Why JavaScript? jonkv interactivity on the web CGI JavaScript Java Applets Netscape LiveScript JavaScript 1: Example Why JavaScript? 2 JavaScript JavaScript the language Web page manipulation with JavaScript and the DOM 1994 1995: Wanted interactivity on the web Server side interactivity: CGI Common Gateway Interface

More information

What did we talk about last time? Examples switch statements

What did we talk about last time? Examples switch statements Week 4 - Friday What did we talk about last time? Examples switch statements History of computers Hardware Software development Basic Java syntax Output with System.out.print() Mechanical Calculation

More information

E ECMAScript, 21 elements collection, HTML, 30 31, 31. Index 161

E ECMAScript, 21 elements collection, HTML, 30 31, 31. Index 161 A element, 108 accessing objects within HTML, using JavaScript, 27 28, 28 activatediv()/deactivatediv(), 114 115, 115 ActiveXObject, AJAX and, 132, 140 adding information to page dynamically, 30, 30,

More information

JavaScript s role on the Web

JavaScript s role on the Web Chris Panayiotou JavaScript s role on the Web JavaScript Programming Language Developed by Netscape for use in Navigator Web Browsers Purpose make web pages (documents) more dynamic and interactive Change

More information

COMS 469: Interactive Media II

COMS 469: Interactive Media II COMS 469: Interactive Media II Agenda Review Data Types & Variables Decisions, Loops, and Functions Review gunkelweb.com/coms469 Review Basic Terminology Computer Languages Interpreted vs. Compiled Client

More information

CHAPTER 6 JAVASCRIPT PART 1

CHAPTER 6 JAVASCRIPT PART 1 CHAPTER 6 JAVASCRIPT PART 1 1 OVERVIEW OF JAVASCRIPT JavaScript is an implementation of the ECMAScript language standard and is typically used to enable programmatic access to computational objects within

More information

Programming language components

Programming language components Programming language components syntax: grammar rules for defining legal statements what's grammatically legal? how are things built up from smaller things? semantics: what things mean what do they compute?

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

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

Unit 20 - Client Side Customisation of Web Pages. Week 4 Lesson 5 Fundamentals of Scripting Unit 20 - Client Side Customisation of Web Pages Week 4 Lesson 5 Fundamentals of Scripting The story so far... three methods of writing CSS: In-line Embedded }These are sometimes called External } block

More information

JavaScript code is inserted between tags, just like normal HTML tags:

JavaScript code is inserted between tags, just like normal HTML tags: Introduction to JavaScript In this lesson we will provide a brief introduction to JavaScript. We won t go into a ton of detail. There are a number of good JavaScript tutorials on the web. What is JavaScript?

More information

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual Contents 1 Introduction...2 2 Lexical Conventions...2 3 Types...3 4 Syntax...3 5 Expressions...4 6 Declarations...8 7 Statements...9

More information

c122mar413.notebook March 06, 2013

c122mar413.notebook March 06, 2013 These are the programs I am going to cover today. 1 2 Javascript is embedded in HTML. The document.write() will write the literal Hello World! to the web page document. Then the alert() puts out a pop

More information

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

Like most objects, String objects need to be created before they can be used. To create a String object, we can write JavaScript Native Objects Broswer Objects JavaScript Native Objects So far we have just been looking at what objects are, how to create them, and how to use them. Now, let's take a look at some of the

More information

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

Note: Java and JavaScript are two completely different languages in both concept and design! 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

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

CISC 1600 Lecture 2.4 Introduction to JavaScript

CISC 1600 Lecture 2.4 Introduction to JavaScript CISC 1600 Lecture 2.4 Introduction to JavaScript Topics: Javascript overview The DOM Variables and objects Selection and Repetition Functions A simple animation What is JavaScript? JavaScript is not Java

More information

The Very Basics of the R Interpreter

The Very Basics of the R Interpreter Chapter 2 The Very Basics of the R Interpreter OK, the computer is fired up. We have R installed. It is time to get started. 1. Start R by double-clicking on the R desktop icon. 2. Alternatively, open

More information

1001ICT Introduction To Programming Lecture Notes

1001ICT Introduction To Programming Lecture Notes 1001ICT Introduction To Programming Lecture Notes School of Information and Communication Technology Griffith University Semester 1, 2015 1 M Environment console M.1 Purpose This environment supports programming

More information

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

PIC 40A. Lecture 10: JS: Wrapper objects, Input and Output, Control structures, random numbers. Copyright 2011 Jukka Virtanen UCLA 1 04/24/17 PIC 40A Lecture 10: JS: Wrapper objects, Input and Output, Control structures, random numbers 04/24/17 Copyright 2011 Jukka Virtanen UCLA 1 Objects in JS In C++ we have classes, in JS we have OBJECTS.

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Chapter 17. Fundamental Concepts Expressed in JavaScript

Chapter 17. Fundamental Concepts Expressed in JavaScript Chapter 17 Fundamental Concepts Expressed in JavaScript Learning Objectives Tell the difference between name, value, and variable List three basic data types and the rules for specifying them in a program

More information

Session 6. JavaScript Part 1. Reading

Session 6. JavaScript Part 1. Reading Session 6 JavaScript Part 1 Reading Reading Wikipedia en.wikipedia.org/wiki/javascript Web Developers Notes www.webdevelopersnotes.com/tutorials/javascript/ JavaScript Debugging www.w3schools.com/js/js_debugging.asp

More information

HTML5 and CSS3 More JavaScript Page 1

HTML5 and CSS3 More JavaScript Page 1 HTML5 and CSS3 More JavaScript Page 1 1 HTML5 and CSS3 MORE JAVASCRIPT 3 4 6 7 9 The Math Object The Math object lets the programmer perform built-in mathematical tasks Includes several mathematical methods

More information

Scheme Quick Reference

Scheme Quick Reference Scheme Quick Reference COSC 18 Fall 2003 This document is a quick reference guide to common features of the Scheme language. It is not intended to be a complete language reference, but it gives terse summaries

More information

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

Lecture 3: The Basics of JavaScript. Background. Needs for Programming Capability. Origin of JavaScript. Using Client-side JavaScript Lecture 3: The Basics of JavaScript Wendy Liu CSC309F Fall 2007 Background Origin and facts 1 2 Needs for Programming Capability XHTML and CSS allows the browser to passively display static content How

More information

JavaScript Functions, Objects and Array

JavaScript Functions, Objects and Array JavaScript Functions, Objects and Array Defining a Function A definition starts with the word function. A name follows that must start with a letter or underscore, followed by any number of letters, digits,

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number

More information

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */ Overview Language Basics This chapter describes the basic elements of Rexx. It discusses the simple components that make up the language. These include script structure, elements of the language, operators,

More information

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

LECTURE-2. Functions review HTML Forms. Arrays Exceptions Events. CS3101: Scripting Languages: Javascript Ramana Isukapalli LECTURE-2 Functions review HTML Forms Arrays Exceptions Events 1 JAVASCRIPT FUNCTIONS, REVIEW Syntax function (params) { // code Note: Parameters do NOT have variable type. 1. Recall: Function

More information

Manju Muralidharan Priya. CS4PM Web Aesthetics and Development WEEK 11

Manju Muralidharan Priya. CS4PM Web Aesthetics and Development WEEK 11 CS4PM Web Aesthetics and Development WEEK 11 Objective: Understand basics of JScript Outline: a. Basics of JScript Reading: Refer to w3schools websites and use the TRY IT YOURSELF editor and play with

More information

Functions. Systems Programming Concepts

Functions. Systems Programming Concepts Functions Systems Programming Concepts Functions Simple Function Example Function Prototype and Declaration Math Library Functions Function Definition Header Files Random Number Generator Call by Value

More information

JQuery and Javascript

JQuery and Javascript JQuery and Javascript Javascript - a programming language to perform calculations/ manipulate HTML and CSS/ make a web page interactive JQuery - a javascript framework to help manipulate HTML and CSS JQuery

More information

Sprite an animation manipulation language Language Reference Manual

Sprite an animation manipulation language Language Reference Manual Sprite an animation manipulation language Language Reference Manual Team Leader Dave Smith Team Members Dan Benamy John Morales Monica Ranadive Table of Contents A. Introduction...3 B. Lexical Conventions...3

More information

C Functions. 5.2 Program Modules in C

C Functions. 5.2 Program Modules in C 1 5 C Functions 5.2 Program Modules in C 2 Functions Modules in C Programs combine user-defined functions with library functions - C standard library has a wide variety of functions Function calls Invoking

More information

Downloaded from Chapter 2. Functions

Downloaded from   Chapter 2. Functions Chapter 2 Functions After studying this lesson, students will be able to: Understand and apply the concept of module programming Write functions Identify and invoke appropriate predefined functions Create

More information

JAVASCRIPT. sarojpandey.com.np/iroz. JavaScript

JAVASCRIPT. sarojpandey.com.np/iroz. JavaScript JAVASCRIPT 1 Introduction JAVASCRIPT is a compact, object-based scripting language for developing client Internet applications. was designed to add interactivity to HTML pages. is a scripting language

More information

COSC 122 Computer Fluency. Programming Basics. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 122 Computer Fluency. Programming Basics. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 122 Computer Fluency Programming Basics Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) We will learn JavaScript to write instructions for the computer.

More information

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh C++ PROGRAMMING For Industrial And Electrical Engineering Instructor: Ruba A. Salamh CHAPTER TWO: Fundamental Data Types Chapter Goals In this chapter, you will learn how to work with numbers and text,

More information

EXERCISE: Introduction to client side JavaScript

EXERCISE: Introduction to client side JavaScript EXERCISE: Introduction to client side JavaScript Barend Köbben Version 1.3 March 23, 2015 Contents 1 Dynamic HTML and scripting 3 2 The scripting language JavaScript 3 3 Using Javascript in a web page

More information

CNIT 129S: Securing Web Applications. Ch 12: Attacking Users: Cross-Site Scripting (XSS) Part 2

CNIT 129S: Securing Web Applications. Ch 12: Attacking Users: Cross-Site Scripting (XSS) Part 2 CNIT 129S: Securing Web Applications Ch 12: Attacking Users: Cross-Site Scripting (XSS) Part 2 Finding and Exploiting XSS Vunerabilities Basic Approach Inject this string into every parameter on every

More information

Session 16. JavaScript Part 1. Reading

Session 16. JavaScript Part 1. Reading Session 16 JavaScript Part 1 1 Reading Reading Wikipedia en.wikipedia.org/wiki/javascript / p W3C www.w3.org/tr/rec-html40/interact/scripts.html Web Developers Notes www.webdevelopersnotes.com/tutorials/javascript/

More information

IDM 232. Scripting for Interactive Digital Media II. IDM 232: Scripting for IDM II 1

IDM 232. Scripting for Interactive Digital Media II. IDM 232: Scripting for IDM II 1 IDM 232 Scripting for Interactive Digital Media II IDM 232: Scripting for IDM II 1 PHP HTML-embedded scripting language IDM 232: Scripting for IDM II 2 Before we dive into code, it's important to understand

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

Syllabus - July to Sept

Syllabus - July to Sept Class IX Sub: Computer Syllabus - July to Sept What is www: The World Wide Web (www, W3) is an information space where documents and other web resources are identified by URIs, interlinked by hypertext

More information

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output Last revised January 12, 2006 Objectives: 1. To introduce arithmetic operators and expressions 2. To introduce variables

More information

Programmazione Web a.a. 2017/2018 HTML5

Programmazione Web a.a. 2017/2018 HTML5 Programmazione Web a.a. 2017/2018 HTML5 PhD Ing.Antonino Raucea antonino.raucea@dieei.unict.it 1 Introduzione HTML HTML is the standard markup language for creating Web pages. HTML stands for Hyper Text

More information

BEGINNING PROBLEM-SOLVING CONCEPTS FOR THE COMPUTER. Chapter 2

BEGINNING PROBLEM-SOLVING CONCEPTS FOR THE COMPUTER. Chapter 2 1 BEGINNING PROBLEM-SOLVING CONCEPTS FOR THE COMPUTER Chapter 2 2 3 Types of Problems that can be solved on computers : Computational problems involving some kind of mathematical processing Logical Problems

More information

INFS 2150 Introduction to Web Development and e-commerce Technology. Programming with JavaScript

INFS 2150 Introduction to Web Development and e-commerce Technology. Programming with JavaScript INFS 2150 Introduction to Web Development and e-commerce Technology Programming with JavaScript 1 Objectives JavaScript client-side programming Example of a JavaScript program The element

More information

Objectives. Introduction to JavaScript. Introduction to JavaScript INFS Peter Y. Wu, RMU 1

Objectives. Introduction to JavaScript. Introduction to JavaScript INFS Peter Y. Wu, RMU 1 Objectives INFS 2150 Introduction to Web Development and e-commerce Technology Programming with JavaScript JavaScript client-side programming Example of a JavaScript program The element

More information

Scheme Quick Reference

Scheme Quick Reference Scheme Quick Reference COSC 18 Winter 2003 February 10, 2003 1 Introduction This document is a quick reference guide to common features of the Scheme language. It is by no means intended to be a complete

More information

INLEDANDE WEBBPROGRAMMERING MED JAVASCRIPT INTRODUCTION TO WEB PROGRAMING USING JAVASCRIPT

INLEDANDE WEBBPROGRAMMERING MED JAVASCRIPT INTRODUCTION TO WEB PROGRAMING USING JAVASCRIPT INLEDANDE WEBBPROGRAMMERING MED JAVASCRIPT INTRODUCTION TO WEB PROGRAMING USING JAVASCRIPT ME152A L4: 1. HIGHER ORDER FUNCTIONS 2. REGULAR EXPRESSIONS 3. JAVASCRIPT - HTML 4. DOM AND EVENTS OUTLINE What

More information

CS112 Lecture: Working with Numbers

CS112 Lecture: Working with Numbers CS112 Lecture: Working with Numbers Last revised January 30, 2008 Objectives: 1. To introduce arithmetic operators and expressions 2. To expand on accessor methods 3. To expand on variables, declarations

More information

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

INTRODUCTION TO WEB DEVELOPMENT AND HTML. Lecture 15: JavaScript loops, Objects, Events - Spring 2011 INTRODUCTION TO WEB DEVELOPMENT AND HTML Lecture 15: JavaScript loops, Objects, Events - Spring 2011 Outline Selection Statements (if, if-else, switch) Loops (for, while, do..while) Built-in Objects: Strings

More information

The PCAT Programming Language Reference Manual

The PCAT Programming Language Reference Manual The PCAT Programming Language Reference Manual Andrew Tolmach and Jingke Li Dept. of Computer Science Portland State University September 27, 1995 (revised October 15, 2002) 1 Introduction The PCAT language

More information

Outline. Introduction to JavaScript Resources What is JavaScript? JavaScript in web pages

Outline. Introduction to JavaScript Resources What is JavaScript? JavaScript in web pages JavaScript CMPT 281 Outline Introduction to JavaScript Resources What is JavaScript? JavaScript in web pages Announcements Layout with tables Assignment 3 JavaScript Resources Resources Why JavaScript?

More information

CS1046 Lab 4. Timing: This lab should take you 85 to 130 minutes. Objectives: By the end of this lab you should be able to:

CS1046 Lab 4. Timing: This lab should take you 85 to 130 minutes. Objectives: By the end of this lab you should be able to: CS1046 Lab 4 Timing: This lab should take you 85 to 130 minutes. Objectives: By the end of this lab you should be able to: Define the terms: function, calling and user-defined function and predefined function

More information

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

Web Programming and Design. MPT Junior Cycle Tutor: Tamara Demonstrators: Aaron, Marion, Hugh Web Programming and Design MPT Junior Cycle Tutor: Tamara Demonstrators: Aaron, Marion, Hugh Plan for the next 5 weeks: Introduction to HTML tags, creating our template file Introduction to CSS and style

More information

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) Technology & Information Management Instructor: Michael Kremer, Ph.D. Class 2 Professional Program: Data Administration and Management JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) AGENDA

More information

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4 BIL 104E Introduction to Scientific and Engineering Computing Lecture 4 Introduction Divide and Conquer Construct a program from smaller pieces or components These smaller pieces are called modules Functions

More information

PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37)

PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37) PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37) A Server-side Scripting Programming Language An Introduction What is PHP? PHP stands for PHP: Hypertext Preprocessor. It is a server-side

More information

A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University 2011 Pearson Prentice Hall ISBN

A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University 2011 Pearson Prentice Hall ISBN A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University 2011 Pearson Prentice Hall ISBN 978-0-13-216675-1 Chapter 5 JavaScript and User Interaction 1 Text Boxes HTML event handlers

More information

Outline. Data and Operations. Data Types. Integral Types

Outline. Data and Operations. Data Types. Integral Types Outline Data and Operations Data Types Arithmetic Operations Strings Variables Declaration Statements Named Constant Assignment Statements Intrinsic (Built-in) Functions Data and Operations Data and Operations

More information