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

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

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

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

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

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

COMS 469: Interactive Media II

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

Product Price Formula extension for Magento2. User Guide

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

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

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

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

Maths Functions User Manual

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

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

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

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

Full file at Tutorial 2: Working with Operators and Expressions

Place User-Defined Functions in the HEAD Section

Chapter 2. Outline. Simple C++ Programs

Such JavaScript Very Wow

Fundamentals of Website Development

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

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

CT 229 Java Syntax Continued

COMS 469: Interactive Media II

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

New Perspectives on Creating Web Pages with HTML. Tutorial Objectives

Events: another simple example

The first sample. What is JavaScript?

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

Introduction to DHTML

C++ Programming Lecture 11 Functions Part I

Custom Variables (Virtual Variables)

Introduction to Python, Cplex and Gurobi

MYSQL NUMERIC FUNCTIONS

ME 142 Engineering Computation I. Unit 1.2 Excel Functions

Programming in MATLAB

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

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

Introduction to JavaScript

Extending Ninox with NX

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

Methods CSC 121 Fall 2014 Howard Rosenthal

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

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

Introduction to MATLAB

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

About the Tutorial. Audience. Prerequisites. Copyright and Disclaimer

Data Types and Basic Calculation

HTML User Interface Controls. Interactive HTML user interfaces. Document Object Model (DOM)

JSF - H:INPUTSECRET. Class name of a validator that s created and attached to a component

Javascript. A key was pressed OR released. A key was released. A mouse button was pressed.

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

Sketchify Tutorial Properties and Variables. sketchify.sf.net Željko Obrenović

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

link document.getelementbyid("coffee").style.borderwidth = "0px" document.getelementbyid("tea").style.borderwidth = "10px"

TEXTAREA NN 2 IE 3 DOM 1

Chapter 1 Introduction to Computers and the Internet

CSC Javascript

DOM Primer Part 2. Contents

TECH TIP VISION Calibration and Data Acquisition Software

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

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

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

Methods CSC 121 Spring 2017 Howard Rosenthal

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

Engineering Problem Solving with C++, Etter/Ingber

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

JavaScript Handling Events Page 1

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

Python Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]

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

Methods CSC 121 Fall 2016 Howard Rosenthal

Quick MATLAB Syntax Guide

Consider this m file that creates a file that you can load data into called rain.txt

C++ Overview. Chapter 1. Chapter 2

Introduction to PartSim and Matlab

JavaScript and XHTML. Prof. D. Krupesha, PESIT, Bangalore

MATELECT PDsoft v1.00

Variable and Data Type 2

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

2 Making Decisions. Store the value 3 in memory location y

Session 16. JavaScript Part 1. Reading

What is a Function? EF102 - Spring, A&S Lecture 4 Matlab Functions

Chapter 4 Basics of JavaScript

Introduction to MATLAB 7 for Engineers

Chapter 4: Basic C Operators

Chapter 1 Introduction to MATLAB

Information Design. Professor Danne Woo! infodesign.dannewoo.com! ARTS 269 Fall 2018 Friday 10:00PM 1:50PM I-Building 212

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 5. Playing with Data Modifiers and Math Functions Getting Controls

Hive Wavetables. Introduction 2. Concepts 3 Some Terminology 3. Commands 4

JSF - H:SELECTONEMENU

. Executable Statements

Session 6. JavaScript Part 1. Reading

Web Engineering (Lecture 06) JavaScript part 2

Introduction to Matlab

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

Operators Functions Order of Operations Mixed Mode Arithmetic VOID Data. Syntax and type conventions Using the Script window interface

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

Transcription:

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 Date Math Arrays

Selection Statements

if if statements allow code to be executed when the condition specified is true. if the condition is true then the code in the curly braces is executed. if (condition) { code to be executed if condition is true }

What this code does? <script type= text/javascript > date = new Date(); time = date.gethours(); if (time < 12) { document.write('good Morning'); } </script>

if-else If the conditions specified are met, run the first block of code; otherwise run the second block. if (condition) { } code to be executed if condition is true else { } code to be executed if condition is false

What this code does? <script type= text/javascript > date = new Date(); time = date.gethours(); if (time < 12) { document.write( Good Morning ); } else { document.write( Good Afternoon ); } </script>

switch A switch statement allows you to deal with several results of a condition. switch (expression) { } case option1: code to be executed if expression is what is written in option1 break; case option2: code to be executed if expression is what is written in option2 break; case option3: code to be executed if expression is what is written in option3 break; default: code to be executed if expression is different from option1, option2, and option3

switch example <p>enter the name of your favorite type of animal that stars in a cartoon:</p> <form name= frmanimal > <input type= text name= txtanimal /><br /> <input type= button value= Check animal onclick= checkanimal() /> </form> function checkanimal() { switch (document.frmanimal.txtanimal.value){ case "rabbit": alert("watch out, it s Elmer Fudd!") break; case "coyote": alert("no match for the road runner - meep meep!") break; case "mouse": alert("watch out Jerry, here comes Tom!") break; default : alert("are you sure you picked an animal from a cartoon?"); } }

Loops!

while In a while loop, a code block is executed if a condition is true and for as long as that condition remains true. The syntax is as follows: while (condition) { code to be executed }

What this code does? <script type="text/javascript"> var i = 1; while (i < 11) { document.write(i + " x 3 = " + (i * 3) + "<br/>" ); i++; } </script>

while Example

do..while A do... while loop executes a block of code once and then checks a condition. For as long as the condition is true it continues to loop. So, whatever the condition, the loop runs at least once Here is the syntax: do { code to be executed } while (condition)

What this code does? <script type="text/javascript"> var i = 12; do { document.write(i + " x 3 = " + (i * 3) + "<br />" ); i++; } while (i < 11) </script>

for The for statement executes a block of code a specified number of times. Use it when you know how many times you want the code to be executed rather than running while a particular condition is true/false. Syntax: for (a; b; c) { code to be executed } a is evaluated before the loop is run, and is only evaluated once. b should be a condition that indicates whether the loop should be run again. if it returns true the loop runs again. c is evaluated after the loop has run.

What this code does? for (i=0; i<20; i++) { } document.write(i + x 3 = + (i * 3) + <br /> );

What about this one? for (i=0; i<20; i++) { } document.write(i + x 3 = + (i * 3) + <br /> ); if( i == 10 ) break;

Events

Events Window events: which occur when something happens to a window. For example, a page loads or unloads. User events: which occur when the user interacts with elements in the page using a mouse (or other pointing device) or a keyboard.

Events onload: Document has finished loading onclick: Button on mouse has been clicked over the element. ondblclick: Button on mouse has been double-clicked over the element. onmousedown: Button on mouse has been pressed (but not released) over the element. onmouseup: Button on mouse (or other pointing device) has been released over the element.

More Events onmouseover: Button on mouse has been moved onto the element. onmousemove: Button on mouse has been moved while over the element. onmouseout: Button on mouse has been moved off the element. onkeypress: A key is pressed and released over the element. onkeydown: A key is held down over an element. onkeyup: A key is released over an element. Most elements

Even more Events onfocus: Element receives focus either by mouse clicking it, tabbing order giving focus to that element, or code giving focus to the element. onblur: Element loses focus. Forms: onsubmit: A form is submitted. onreset:a form is reset. onselect: User selects some text in a text field. onchange: A control loses input focus and its value has been changed since gaining focus.

Built-in Objects! String, Date

String Allows you to deal with strings of text: mystring = new String('Here is some big text') document.write(mystring); Why we just don't use? var sometext = "Here is some big text"; document.write(sometext);

String methods charat(index): Returns the character at a specified position. String text = new String("Good Morning"); text.charat(3) would return the letter d. link(targeturl): Creates a link text.link("http://www.google.com") <a href="http://www.google.com">good Morning</a> substr(start, length): Returns a substring starting at the position start and then length consecutive characters.

String methods substring(startposition, endposition): returns a substring from position startposition to the position endposition tolowercase(): Converts a string to lowercase String text = new String("John Smith") text.tolowercase() john smith touppercase(): Converts a string to uppercase text.touppercase() JOHN SMITH

Date Date object helps you work with dates and times new Date() To set a specific date or time, you need to pass only one of these parameters: milliseconds: number of milliseconds since 01/01/1970. yr_num, mo_num, day_num: Represents year, month, and day. yr_num, mo_num, day_num, hr_num, min_num, seconds_num, ms_num: Represents the years, days, hours, minutes, seconds, and milliseconds.

Date Methods getdate() : returns the date (from 1 to 31) getday(): returns the day (from 0 to 6; Sunday, to Saturday) getmonth(): returns the month (from 0 to 11; January to December) getyear(): returns the year using two digits getfullyear(): returns the year using four-digit year

Date Methods (Cont'd) gethours(): returns the hour getminutes(): returns the minute getseconds(): returns the seconds gettimezoneoffset(): returns the time difference between the user's computer and GMT

Date Methods (Cont'd) setdate(): sets the date of the month (from 1 to 31). setfullyear(): sets the year (four digits). sethours(): sets the hour (from 0 to 23). setminutes(): Sets the minute (from 0 to 59). setmonth(): Sets the month (from 0 to 11; 0=January, 1=February). setseconds(): Sets the second (from 0 to 59).

Dates Examples With datestring, and will read Wed Apr 16 00:00:00 UTC+0100 1975: var birthdate = new Date( April 16, 1975 ) document.write(birthdate) With yr_num, mo_num, and day_num, and will read Mon May 12 00:00:00 UTC+0100 1975: var birthdate = new Date(1975, 4, 28) document.write(birthdate)

Math The math object helps in working with numbers. Example: numberpi = Math.PI document.write (numberpi) Another Example: numberpi = Math.PI numberpi = Math.round(numberPI) document.write (numberpi)

Math methods abs(x): Returns the absolute value of x. acos(x): Returns the arccosine of x. asin(x): Returns the arcsine of x. atan(x): Returns the arctangent of x. atan2(y,x): Returns the angle from the x-axis to a point. ceil(x): Returns the nearest integer greater than or equal to x. cos(x): Returns the cosine of x. sqrt(x): Returns the square root of x. tan(x): Returns the tangent of x.

Math methods exp(x): Returns the value of E raised to the power of x. floor(x): Returns the nearest integer less than or equal to x. log(x): Returns the natural log of x. max(x,y): Returns the number with the highest value of x and y. min(x,y): Returns the number with the lowest value of x and y. pow(x,y): Returns the value of the number x raised to the power of y. random(): Returns a random number between 0 and 1. round(x): Rounds x to the nearest integer. sin(x): Returns the sine of x.

Arrays An array can hold more than one value. These values can be accessed individually. We need to use a Constructor to build up the array: instruments = new Array("guitar", "drums","piano") The elements of the array are indexed using their ordinal number, starting at 0. instruments[0] returns the guitar. instruments[1] returns the drums. instruments[2] returns the piano.

Arrays (Cont'd) If you do not want to provide all the values when you create the array, you can just indicate how many elements you want to be able to hold: var instruments = new Array(3) To change the size of an array, just modify the length property, such as: instruments.length = 5 document.write(instruments.length) will print 5

Array Methods concat(): Joins two or more arrays to create one new one. join(separator): Joins all of the elements of an array together separated by the character specified as a separator (the default is a comma); reverse(): Returns the array reversed slice(): Returns a specified part of the array sort(): Returns a sorted array

Examples Find the examples in the course website

Get Dojo! <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js" type="text/javascript"></script>

Cool Examples with Dojo!!! See Examples in course site

Questions?