Introduction to JavaScript Pat Morin COMP Outline What is JavaScript? – History – Uses Adding JavaScript to HTML JavaScript syntax JavaScript events.

Slides:



Advertisements
Similar presentations
JavaScript FaaDoOEngineers.com FaaDoOEngineers.com.
Advertisements

JavaScript and the DOM Les Carr COMP3001 Les Carr COMP3001.
1 CSC 551: Web Programming Spring 2004 client-side programming with JavaScript  scripts vs. programs  JavaScript vs. JScript vs. VBScript  common tasks.
The Web Warrior Guide to Web Design Technologies
JavaScript Forms Form Validation Cookies. What JavaScript can do  Control document appearance and content  Control the browser  Interact with user.
JavaScript (Part 2) CS 183 4/13/2010. JavaScript (Part 2) Will cover: ◦ For.. In ◦ Events ◦ Try.. Catch, Throw ◦ Objects.
Multimedia and the World Wide Web HCI 201 Lecture Notes #8B.
JavaScript Forms Form Validation Cookies CGI Programs.
Information Technology Center Hany Abdelwahab Computer Specialist.
Form Handling, Validation and Functions. Form Handling Forms are a graphical user interfaces (GUIs) that enables the interaction between users and servers.
JS: DOM Form Form Object Form Object –The Form object represents an HTML form. –For each instance of a tag in an HTML document, a Form object is created.
_______________________________________________________________________________________________________________ E-Commerce: Fundamentals and Applications1.
Scripting Languages.
JavaScript Defined DOM (Document Object Model) General Syntax Body vs. Head Variables Math & Logic Selection Functions & Events Loops Animation Getting.
Test Automation For Web-Based Applications Portnov Computer School Presenter: Ellie Skobel.
Bridges To Computing General Information: This document was created for use in the "Bridges to Computing" project of Brooklyn College. You are invited.
Unobtrusive JavaScript
IT – som værktøj Bent Thomsen Institut for Datalogi Aalborg Universitet.
Copyright © 2002 ProsoftTraining. All rights reserved. JavaScript Fundamentals.
JavaScript & DOM Client-side scripting. JavaScript JavaScript is a tool to automate client side (which is implemented using HTML so far) JavaSript syntax.
DOM and JavaScript Aryo Pinandito.
1 JavaScript: Objects and Object Models October 25, 2005 Slides modified from Internet & World Wide Web: How to Program (3rd) edition. By Deitel,
Javascript. Outline Introduction Fundamental of JavaScript Javascript events management DOM and Dynamic HTML (DHTML)
Lesson13. JavaScript JavaScript is an interpreted language, designed to function within a web browser. It can also be used on the server.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
Client-Side Scripting JavaScript.  produced by Netscape for use within HTML Web pages.  built into all the major modern browsers. properties  lightweight,
Chapter 8 Collecting Data with Forms. Chapter 8 Lessons Introduction 1.Plan and create a form 2.Edit and format a form 3.Work with form objects 4.Test.
JavaScript, jQuery, and Mashups Incorporating JavaScript, jQuery, and other Mashups into existing pages.
Lecture 10 JavaScript: DOM and Dynamic HTML Boriana Koleva Room: C54
1 JavaScript
JavaScript - Basic Concepts Prepared and Presented by Hienvinh Nguyen, Afshin Tiraie.
Overview of Form and Javascript fundamentals. Brief matching exercise 1. This is the software that allows a user to access and view HTML documents 2.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
JavaScript Introduction.  JavaScript is a scripting language  A scripting language is a lightweight programming language  A JavaScript can be inserted.
Jaana Holvikivi 1 Introduction to Javascript Jaana Holvikivi Metropolia.
1 CSC160 Chapter 7: Events and Event Handlers. 2 Outline Event and event handlers onClick event handler onMouseOver event handler onMouseOut event handler.
©SoftMooreSlide 1 Introduction to HTML: Forms ©SoftMooreSlide 2 Forms Forms provide a simple mechanism for collecting user data and submitting it to.
Introduction to HTML. _______________________________________________________________________________________________________________ 2 Outline Key issues.
JavaScript Defined DOM (Document Object Model) General Syntax Body vs. Head Variables Math & Logic Selection Functions & Events Loops Animation Getting.
CIS 3.5 Lecture 2.3 "Introduction to JavaScript".
JavaScript Event Handlers. Introduction An event handler executes a segment of a code based on certain events occurring within the application, such as.
LESSON : EVENTS AND FORM VALIDATION -JAVASCRIPT. EVENTS CLICK.
Javascript Basic Concepts Presentation By: Er. Sunny Chanday Lecturer CSE/IT RBIENT.
JavaScript and Ajax (JavaScript Environment) Week 6 Web site:
Chapter 4 Java Script – Part2. 2 Location object Properties Properties href – whole path will be displayed. ex: window.location.href ( see example 11)
© 2007 D. J. ForemanJS-m1 String, Math & Miscellaneous Methods & Properties.
Introduction to JavaScript MIS 3502, Fall 2016 Jeremy Shafer Department of MIS Fox School of Business Temple University 9/29/2016.
Introduction to.
JavaScript and HTML Simple Event Handling 11-May-18.
Applied Component I Unit II Introduction of java-script
CIIT-Human Computer Interaction-CSC456-Fall-2015-Mr
JavaScript is a programming language designed for Web pages.
Web Development & Design Foundations with HTML5 7th Edition
JAVASCRIPTS AND HTML DOCUMENTS
JavaScript for Beginners
14 A Brief Look at JavaScript and jQuery.
JavaScript and HTML Simple Event Handling 19-Sep-18.
JavaScript Introduction
DHTML Javascript Internet Technology.
String, Math & Miscellaneous Methods & Properties
DHTML Javascript Internet Technology.
JavaScript Basics What is JavaScript?
JavaScript is a scripting language designed for Web pages by Netscape.
Javascript & DOM.
Web Programming and Design
String, Math & Miscellaneous Methods & Properties
JavaScript for Beginners
Web Programming and Design
JavaScript and HTML Simple Event Handling 26-Aug-19.
JavaScript and HTML Simple Event Handling 4-Oct-19.
Presentation transcript:

Introduction to JavaScript Pat Morin COMP2405

2 Outline What is JavaScript? – History – Uses Adding JavaScript to HTML JavaScript syntax JavaScript events JavaScript classes The HTML Document Object Model

3 What is JavaScript? JavaScript is a programming language for use in HTML pages Invented in 1995 at Netscape Corporation (LiveScript) JavaScript has nothing to do with Java JavaScript programs are run by an interpreter built into the user's web browser (not on the server)

4 Where does JavaScript Fit In? Recall 1. client opens connection to server 2. client sends request to server 3. server sends response to client 4. client and server close connection What about Step 5? 5. Client renders (displays) the response received from server Step 5 involves displaying HTML And running any JavaScript code within the HTML

5 What can JavaScript Do? JavaScript can dynamically modify an HTML page JavaScript can react to user input JavaScript can validate user input JavaScript can be used to create cookies (yum!) JavaScript is a full-featured programming language JavaScript user interaction does not require any communication with the server

6 Pros and Cons of JavaScript Pros: – Allows more dynamic HTML pages, even complete web applications Cons: – Requires a JavaScript-enabled browser – Requires a client who trusts the server enough to run the code the server provides JavaScript has some protection in place but can still cause security problems for clients – Remember JavaScript was invented in 1995 and web- browsers have changed a lot since then

7 Using JavaScript in your HTML JavaScript can be inserted into documents by using the SCRIPT tag Hello World in JavaScript document.write("Hello World!");

8 Where to Put your Scripts You can have any number of scripts Scripts can be placed in the HEAD or in the BODY – In the HEAD, scripts are run before the page is displayed – In the BODY, scripts are run as the page is displayed In the HEAD is the right place to define functions and variables that are used by scripts within the BODY

9 Using JavaScript in your HTML Hello World in JavaScript function helloWorld() { document.write("Hello World!"); } helloWorld();

10 External Scripts Scripts can also be loaded from an external file This is useful if you have a complicated script or set of subroutines that are used in several different documents

11 JavaScript Variables JavaScript has variables that you can declare with the optional var keyword Variables declared within a function are local to that function Variables declared outside of any function are global variables var myname = "Pat Morin";

12 JavaScript Operators and Constructs JavaScript has most of the operators we're used to from C/Java – Arithmetic (+, -, *, /, %) – Assignment (=, +=, -=, *= /=, %=, ++, --) – Logical (&&, ||, !) – Comparison (, =, ==) Note: + also does string concatentation Constructs: – if, else, while, for, switch, case

13 Simple User Interaction There are three built-in methods of doing simple user interaction – alert(msg) alerts the user that something has happened – confirm(msg) asks the user to confirm (or cancel) something – prompt(msg, default) asks the user to enter some text alert("There's a monster on the wing!"); confirm("Are you sure you want to do that?"); prompt("Enter you name", "Adam");

14 JavaScript Functions JavaScript lets you define functions using the function keyword Functions can return values using the return keyword function showConfirm() { confirm("Are you sure you want to do that?"); }

15 JavaScript Arrays JavaScript has arrays that are indexed starting at 0 Special version of for works with arrays var colors = new Array(); colors[0] = "red"; colors[1] = "green"; colors[2] = "blue"; colors[3] = "orange"; colors[4] = "magenta"; colors[5] = "cyan"; for (var i in colors) { document.write("<div style=\"background-color:" + colors[i] + ";\">" + colors[i] + " \n"); }

16 JavaScript Events JavaScript can be made to respond to user events Common Events: – onload and onunload : when a page is first visited or left – onfocus, onblur, onchange : events pertaining to form elements – onsubmit : when a form is submitted – onmouseover, onmouseout : for "menu effects" A complete list of event types is available here –

17 Exception Handling JavaScript also has try, catch, and throw keywords for handling JavaScript errors try { runSomeCode(); } catch(err) { var txt="There was an error on this page.\n\n" + "Error description: " + err.description + "\n\n" alert(txt) }

18 Comments in JavaScript Comments in JavaScript are delimited with // and /* */ as in Java and C++

19 JavaScript Objects JavaScript is object-oriented and uses the same method-calling syntax as Java We have already seen this with the document object document.write("Hello World!");

20 Built-In JavaScript Objects Some basic objects are built-in to JavaScript – String – Date – Array – Boolean – Math

21 JavaScript Strings A String object is created every time you use a string literal (just like in Java) Have many of the same methods as in Java – charAt, concat, indexOf, lastIndexOf, match, replace, search, slice, split, substr, substring, toLowerCase, toUpperCase, valueOf There are also some HTML specific methods – big, blink, bold, fixed, fontcolor, fontsize, italics, link, small, strike, sub, sup Don't use the HTML methods (use CSS instead) – This is the worst kind of visual formatting

22 JavaScript Dates The Date class makes working with dates easier A new date is initialized with the current date Dates can be compared and incremented var myDate = new Date(); myDate.setFullYear(2007,2,14); var today = new Date(); var nextWeek = today + 7; if (nextWeek > today) { alert("You have less than one week left"); }

23 JavaScript Arrays and Booleans We have already seen the Array class The Boolean class encapsulates a boolean value

24 The JavaScript Math Class The Math class encapsulates many commonly- used mathematical entities and formulas These are all class methods – abs, acos, asin, atan, atan2, ceil, cos, exp, floor, log, max, min, pow, random, round, sin, sqrt, tan These are all class methods – E, LN2, LN10, LOG2E, LOG10E, PI, SQRT1_2, SQRT2 if (Math.cos(Math.PI) != 0) { alert("Something is wrong with Math.cos"); }

25 JavaScript and the DOM The Document Object Model (DOM) is a specification that determines a mapping between programming language objects and the elements of an HTML document Not specific to JavaScript

26 HTML DOM Objects Environment objects – Window, Navigator, Screen, History, Location, Document HTML objects – Anchor, Area, Base, Body, Button, Event, Form, Frame, Frameset, Iframe, Image, Checkbox, FileUpload, Hidden, Password, Radio, Reset, Submit, Text, Link, Meta, Object, Option, Select, Style, Table, TableCell, TableRow, TextArea

27 HTML DOM: Document The Document object represents an HTML document and can be used to access all documents in a page A Document contains several collections – anchors, forms, images, links Has several properties – body, cookie, domain, lastModified, referrer, title, URL Has several useful methods – getElementById, getElementsByName, getElementsByTagName, write, writeln, open, close

28 HTML DOM: Document An instance of Document is already created for you, called document function changeF() { var cText = document.getElementById("c"); var fText = document.getElementById("f");... }... C F

29 HTML DOM: Form Elements One of the most common uses of JavaScript is for form validation Several HTML DOM classes encapsulate form elements – Form, Button, Checkbox, Hidden, Password, Text, Radio, Reset, Submit, Textarea Warning: Using JavaScript is not a substitute for validating form data in CGI scripts

30 HTML DOM: Text A text entry field (input type="text") is encapsulated by a Text object Variables – value, maxLength, id, size, name, tabindex, readOnly Changing these variables has an immediate effect on the displayed data

31 HTML DOM: The Document Tree Accessing elements and changing their properties lets us do simple things like form validation, data transfer etc HTML DOM lets us do much more We can create, delete, and modify parts of the HTML document For this we need to understand the Document Tree

32 HTML DOM: The Document Tree

33 Navigating the Document Tree With JavaScript we can navigate the document tree document.getElementById(), getElementsByName(), and getElementsByTagName() return nodes in the document tree Information can be obtained from – nodeName – The tag name – nodeValue – The the text of a text node – nodeType – The kind of node

34