Web Programming/Scripting: JavaScript

Similar documents
Session 16. JavaScript Part 1. Reading

Session 6. JavaScript Part 1. Reading

Introduction to JavaScript

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

The first sample. What is JavaScript?

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

<form>. input elements. </form>

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

JavaScript is described in detail in many books on the subject, and there is excellent tutorial material at

CISC 1600 Lecture 2.4 Introduction to JavaScript

Q1. What is JavaScript?

Place User-Defined Functions in the HEAD Section

JavaScript Introduction

COMS W3101: SCRIPTING LANGUAGES: JAVASCRIPT (FALL 2017)

A Balanced Introduction to Computer Science, 3/E

CITS1231 Web Technologies. JavaScript

Exercise 1: Basic HTML and JavaScript

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

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

INTRODUCTION TO WEB DEVELOPMENT AND HTML. Lecture 13: Intro to JavaScript - Spring 2011

Project 3 Web Security Part 1. Outline

(Refer Slide Time: 01:40)

JavaScript s role on the Web

JavaScript!= Java. Intro to JavaScript. What is JavaScript? Intro to JavaScript 4/17/2013 INTRODUCTION TO WEB DEVELOPMENT AND HTML

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

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

CSC Web Programming. Introduction to JavaScript

CHAPTER 6 JAVASCRIPT PART 1

JavaScript Introduction

Web Site Development with HTML/JavaScrip

Web Development & Design Foundations with HTML5, 8 th Edition Instructor Materials Chapter 14 Test Bank

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

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

Client-side Techniques. Client-side Techniques HTML/XHTML. Static web pages, Interactive web page: without depending on interaction with a server

JavaScript. What s wrong with JavaScript?

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

PIC 40A. Midterm 1 Review

CIW 1D CIW JavaScript Specialist.

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

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

5. JavaScript Basics

INLEDANDE WEBBPROGRAMMERING MED JAVASCRIPT INTRODUCTION TO WEB PROGRAMING USING JAVASCRIPT

(from Chapters 10/11 of the text)

JavaScript Introduction

Web Development & Design Foundations with HTML5

Programing for Digital Media EE1707. Lecture 3 JavaScript By: A. Mousavi and P. Broomhead SERG, School of Engineering Design, Brunel University, UK

Introduction to using HTML to design webpages

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

JavaScript: The Basics

Web Engineering (Lecture 06) JavaScript part 2

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

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

Project 2: After Image

CGS 3066: Spring 2015 JavaScript Reference

Controlled Assessment Task. Question 1 - Describe how this HTML code produces the form displayed in the browser.

JavaScript By: A. Mousavi & P. Broomhead SERG, School of Engineering Design, Brunel University, UK

Client vs Server Scripting

COMS 469: Interactive Media II

8/19/2018. Web Development & Design Foundations with HTML5. Learning Objectives (1 of 2) Learning Objectives (2 of 2) What is JavaScript?

Manju Muralidharan Priya. CS4PM Web Aesthetics and Development WEEK 11

UNIT -II. Language-History and Versions Introduction JavaScript in Perspective-

COMP519 Practical 5 JavaScript (1)

Web Designing Course

Javascript. UNIVERSITY OF MASSACHUSETTS AMHERST CMPSCI 120 Fall 2010

PIC 40A. Review for the Final. Copyright 2011 Jukka Virtanen UCLA 1 06/05/15

CS 110 Exam 2 Spring 2011

Introduction to DHTML

JavaScript by Vetri. Creating a Programmable Web Page

UNIT 3 SECTION 1 Answer the following questions Q.1: What is an editor? editor editor Q.2: What do you understand by a web browser?

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

React. HTML code is made up of tags. In the example below, <head> is an opening tag and </head> is the matching closing tag.

Lesson 5: Introduction to Events

Mobile Site Development

HTML 5 and CSS 3, Illustrated Complete. Unit L: Programming Web Pages with JavaScript

Chapter 3 - Simple JavaScript - Programming Basics. Lesson 1 - JavaScript: What is it and what does it look like?

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:

Basics of JavaScript. Last Week. Needs for Programming Capability. Browser as Development Platform. Using Client-side JavaScript. Origin of JavaScript

Software. Programming Languages. Types of Software. Types of Languages. Types of Programming. Software does something

Lesson 6: Introduction to Functions

Loops/Confirm Tutorial:

This course is designed for web developers that want to learn HTML5, CSS3, JavaScript and jquery.

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

COMP519 Web Programming Lecture 16: JavaScript (Part 7) Handouts

CIS 228 (Spring, 2012) Final, 5/17/12

Functions. INFO/CSE 100, Spring 2006 Fluency in Information Technology.

Getting Started with

Web Programming/Scripting: PHP and AJAX Refresher

T his article is downloaded from

JavaScript: Introduction, Types

Basics of Web Design, 3 rd Edition Instructor Materials Chapter 2 Test Bank

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

Web Programming HTML CSS JavaScript Step by step Exercises Hans-Petter Halvorsen

CSC Web Programming. JavaScript Browser Objects

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

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

Week 1 - Overview of HTML and Introduction to JavaScript

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

1. Cascading Style Sheet and JavaScript

Working with JavaScript

Sections and Articles

Transcription:

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! What is JavaScript?! Document Properties! JavaScript Syntax! Event Handlers! Built-in JavaScript Objects! Exercise: Creating a Countdown Clock! Pop-Ups and Functions 2

JavaScript! A scripting language designed to add interactivity to HTML page» lightweight programming language! Usually embedded directly into HTML pages! Interpreted language» needs no preliminary compilation! Similar in syntax to Java, but not Java 3 JavaScript Capabilities! Gives HTML designers a programming tool! Can be used to» Put dynamic text into an HTML page» React to events " ex: open new windows, changing images as mouse moves over» Read and write HTML elements» Validate entered data» Detect the visitor s browser» Create cookies 4

JavaScript and Browsers! Since JavaScript is mainly client-side, it can be disabled at the user s browser» or the browser may not support JavaScript! We need to make sure that the web page is still understandable even if JavaScript is turned off» or at least give the user a message if they are not using JavaScript 5 Client-Side JavaScript! Interpreted by the browser upon running» Displaying the page as read and executing JavaScript statements! Can respond to user events! Generally embedded in HTML file! Can also be specified in separate file (with extension.js) 6

Outline! What is JavaScript?! Document Properties! JavaScript Syntax! Event Handlers! Built-in JavaScript Objects! Exercise: Creating a Countdown Clock! Pop-Ups and Functions 7 JavaScript Comments! Comments in HTML <!-- This is a comment -->! Comments in JavaScript» Single line // This is a comment Older browsers do not understand JavaScript. Without commenting out the JavaScript code, an older browser would display the code as regular text.» Multiple lines /* Starting comment Ending comment */ 8

Including JavaScript! JavaScript inside HTML (for XHTML validation), use: <script type= text/javascript > <!-- // needed to start the entire JavaScript code JavaScript code /* comments for the code */ JavaScript code // next line needed to end the entire JavaScript code! JavaScript in a separate file, use: <script src= scriptname.js type= text/javascript > 9 Programming Elements! Declare a variable» var variablename = value;! Conditional» if (condition) {statements;} else {statements;}! Loops» while (condition) {statements;}» do {statements;} while (condition)» for (initial value; condition; update) {statements;}! Functions» function functionname (var1,var2,...,varx) {statements;} 10

Outline! What is JavaScript?! Document Properties! JavaScript Syntax! Event Handlers! Built-in JavaScript Objects! Exercise: Creating a Countdown Clock! Pop-Ups and Functions 11 Useful JavaScript Objects! Document! Location! Date! Navigator! Event! Screen! Form! Window https://developer.mozilla.org/en/gecko_dom_reference 12

Useful Document Methods! write ( string )» write to the document as it s loading! writeln ( string )» write to the document as it s loading and insert a newline character at the end! getelementbyid("string")» access any element on the page via its id attribute» can alter the element using.innerhtml https://developer.mozilla.org/en/dom/document 13 JavaScript Example Display a Message Script in <head> <head> <title>document.write Example 1</title> <script type="text/javascript"> <!-- document.write ("This is a message written when the page starts to load."); </head> <body> <h1>document.write Example 1</h1> <?xml>, <!DOCTYPE>, <html> tags omitted to save space <p>this is an example of including JavaScript in the HTML header.</p> </body> http://www.cs.odu.edu/~mweigle/cs312/js/write-head.html 14

JavaScript Example Display a Message - Script in <body> <head> <title>document.write Example 2</title> </head> <body> <script type="text/javascript"> <!-- document.write ("This is a message written when the page starts to load."); <h1>document.write Example 2</h1> <p>this is an example of including JavaScript in the HTML body.</p> </body> http://www.cs.odu.edu/~mweigle/cs312/js/write-body.html 15 JavaScript Example Display a Message using getelementbyid <head> <title>getelementbyid Example</title> </head> <body> <h1>getelementbyid Example</h1> Named element has to appear before getelementbyid <p>this is an example of using getelementbyid to add text.</p> <div id="target"></div> <script type="text/javascript"> <!-- document.getelementbyid("target").innerhtml = "<em>this text is written by the script.</em>"; http://www.cs.odu.edu/~mweigle/cs312/js/getelementbyid.html </body> 16

Outline! What is JavaScript?! Document Properties! JavaScript Syntax! Event Handlers! Built-in JavaScript Objects! Exercise: Creating a Countdown Clock! Pop-Ups and Functions 17 Alerts! Alerts are pop-up boxes with buttons» alert("sometext"); " Pops up a box that says sometext! Prompts» prompt("sometext","defaultvalue"); " Pops up a box that asks for user input " If the user clicks "OK" the box returns the input value " If the user clicks "Cancel" the box returns null. 18

Example Function with Alert <body> <h1>alert Example (with a Function)</h1> <script type="text/javascript"> <!-- function displaymessage() { alert ("Hello World!"); } function definition function call <p>press the button to display the message.</p> <input type="button" value="click Here" onclick="displaymessage()" /> </body> http://www.cs.odu.edu/~mweigle/cs312/js/alert.html 19 Example Function with Prompt <head> <title>prompt Example</title> <script type="text/javascript"> <!-- function display_prompt() { var name = prompt ("Please enter your name","harry Potter"); return name; } </head> <body> <h1>prompt Example (with a Value-Returning Function)</h1> <script type="text/javascript"> <!-- document.write ("<h3>welcome " + display_prompt() + "!</h3>"); </body> http://www.cs.odu.edu/~mweigle/cs312/js/prompt.html 20

Passing Arguments to a Function JavaScript and Forms <script type= text/javascript > <!-- function useralert (label) { alert (label.value); } <form action=""> <label> Enter alert text: <input type= text name= alerttext /> </label> <br /> <input type= button value= Submit onclick= useralert (alerttext) /> </form> http://www.cs.odu.edu/~mweigle/cs312/js/passing-args.html 21 JavaScript and Forms Accessing Form Data! document.forms[i].inputname.value is a String» what the user typed in the box named inputname in the form with index i (starting at 0) <form action=""> <label>enter name: <input type="text" name="myname" /> </label> </form> document.forms[0].myname.value is the String that the user types in the box! 22

JavaScript and Forms Validating Form Data <script type= text/javascript > <!-- function validateform() { if (document.forms[0].email.value == "") { alert ("You must enter an email address."); } else if (document.forms[0].email.value.search("@") == -1) { alert ("You entered an invalid email address."); } } If the search text does not appear in the string, -1 will be returned. What do we need to add to make the alert show the entered text if it's OK? <form action=""> <label>email: <input type= text name= email /> </label> <br /> <input type= button value= Submit onclick= validateform() /> </form> http://www.cs.odu.edu/~mweigle/cs312/js/validate.html 23 Outline! What is JavaScript?! Document Properties! JavaScript Syntax! Event Handlers! Built-in JavaScript Objects! Exercise: Creating a Countdown Clock! Pop-Ups and Functions 24

Useful Document Properties! URL» returns URL of the current document! lastmodified» returns date and time document was last modified! body.style.backgroundcolor» specifies the background color of the document! links[]» an array containing all of the links on the page! referrer» string that specifies the URL of the page that contained the link to the current page https://developer.mozilla.org/en/dom/document 25 Example Greeting According to Time of Day <script type="text/javascript"> <!-- var d = new Date(); var hrs = d.gethours(); if (hrs < 12) { document. body.style.backgroundcolor = #ffff99 ; document.write ("<h3>good morning!</h3>"); } else { document. body.style.backgroundcolor = #99ff66 ; document.write ("<h3>good day!</h3>"); } http://www.cs.odu.edu/~mweigle/cs312/js/greeting.html <p>the current time is <script type="text/javascript"> <!-- document.write (new Date().toLocaleTimeString()); </p> 26

Outline! What is JavaScript?! Document Properties! JavaScript Syntax! Event Handlers! Built-in JavaScript Objects! Exercise: Creating a Countdown Clock! Pop-Ups and Functions 27 JavaScript Event Handlers! Allows a JavaScript function to be executed when the user does something! onclick» when the mouse clicks an object! onload» when the page or image is finished loading! onmouseover» when the mouse is moved over an element http://www.w3schools.com/jsref/dom_obj_event.asp 28

Example Alert on Click, Using External File <head> <script type="text/javascript" src="externalfunction.js"> </head> <body> <p onclick="start()"> If you click on this paragraph, then it will call an external script function named "start" in the file named "externalfunction.js". Click anywhere in this paragraph and you ll get an alert.</p> <p>another paragraph, click and no alert.</p> </body> 29 Example Alert on Click, Using External File http://www.cs.odu.edu/~mweigle/cs312/js/click.html externalfunction.js: function start() { alert ( Hello, glad you clicked!"); } externalfunction.js must be in the same directory as the HTML file that uses it, or the directory must be specified in the HTML file (src attribute) and must be chmod 644. 30

Exercise! Write JavaScript and XHTML code that meets the following requirements:» page title is JavaScript Exercise» level 1 heading JavaScript Exercise» create a div with the id target and red text» create a paragraph with a gray background and yellow text that reads Click Here! " when the users clicks in the paragraph, the JavaScript function click() should be called» the click() function should write the word CLICK! in the target div Before: After: 31 Outline! What is JavaScript?! Document Properties! JavaScript Syntax! Event Handlers! Built-in JavaScript Objects! Exercise: Creating a Countdown Clock! Pop-Ups and Functions 32

Exercise: Create Countdown Clock! We're going to create a page that has a countdown timer, updating the time until our final exam. http://www.cs.odu.edu/~mweigle/cs312/js/countdown.html 33 Exercise: Create Countdown Clock! What information do we need?! What steps do we need to take? 34

Exercise: Create Countdown Clock Useful Objects/Methods! Target date» target = new Date (string);» format: mm/dd/yyyy hh:mm AM/PM» example: new Date ( 12/10/2011 3:45 PM )! Current date/time» now = new Date();! Date differences» new Date (target now);» difference in milliseconds 35 Exercise: Create Countdown Clock Useful Objects/Methods! Write text to a certain section» getelementbyid("name").innerhtml! Math functions» Math.floor (3/2) " will return 1! Calling functions repeatedly» setinterval ( function(), milliseconds); 36

Exercise: Create Countdown Clock Setup HTML <p>we re counting down until the CS 312 final exam (Dec 10, 2011 @ 3:45pm).</p> <div id= examcountdown style= background-color: blue; color: yellow; font-weight: bold; text-align: center ></div> 37 Exercise: Create Countdown Clock Setup JavaScript <script type= text/javascript > <!-- // set the target date and time var examdate = new Date ( 12/10/2011 3:45 PM ); /* call the function to display the time left until examdate in the area labeled examcountdown */ displaytimeleft (examdate, examcountdown ); // call the function every 1000 ms (every 1 second) setinterval ( displaytimeleft(examdate, examcountdown ), 1000); http://www.cs.odu.edu/~mweigle/cs312/js/countdown.html 38

Exercise: Create Countdown Clock Setup JavaScript displaytimeleft function function displaytimeleft (date, label) { var now = new Date(); var diff = new Date (date now); // in ms var secs = Math.floor (diff.valueof()/1000); if (secs < 0) { document.getelementbyid(label).innerhtml = It s already past! ; return; } http://www.cs.odu.edu/~mweigle/cs312/js/countdown.html 39 Exercise: Create Countdown Clock Setup JavaScript displaytimeleft function // calculate days, hours, minutes, seconds var days = Math.floor (secs / 86400); var leftover = secs % 86400; // 86,400 secs / day var hours = Math.floor (leftover / 3600); // 3,600 secs / hour leftover = leftover % 3600; var mins = Math.floor (leftover / 60); leftover = leftover % 60; // 60 secs / min http://www.cs.odu.edu/~mweigle/cs312/js/countdown.html 40

Exercise: Create Countdown Clock Setup JavaScript displaytimeleft function // setup string to display var display = days + days, + hours + hours, + mins + minutes, + leftover + seconds ; // set the text of the countdown element document.getelementbyid(label).innerhtml = display; } // end of function http://www.cs.odu.edu/~mweigle/cs312/js/countdown.html 41 Outline! What is JavaScript?! Document Properties! JavaScript Syntax! Event Handlers! Built-in JavaScript Objects! Exercise: Creating a Countdown Clock! Pop-Ups and Functions 42