Produced by. App Development & Modeling. BSc in Applied Computing. Eamonn de Leastar

Similar documents
CSI 3140 WWW Structures, Techniques and Standards. Browsers and the DOM

JavaScript and Events

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

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

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

As we design and build out our HTML pages, there are some basics that we may follow for each page, site, and application.

Photo from DOM

5. JavaScript Basics

CITS3403 Agile Web Development Semester 1, 2018

jmaki Overview Sang Shin Java Technology Architect Sun Microsystems, Inc.

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

Session 16. JavaScript Part 1. Reading

CGS 3066: Spring 2015 JavaScript Reference

Web Development & Design Foundations with HTML5

729G26 Interaction Programming. Lecture 4

<form>. input elements. </form>

CSC Web Programming. Introduction to JavaScript

Catching Events. Bok, Jong Soon

1. Cascading Style Sheet and JavaScript

JSF. JSF and Ajax Basics

Unit Notes. ICAWEB411A Produce basic client-side script for dynamic web pages Topic 1 Introduction to JavaScript

Introduction to JavaScript

Markup Language. Made up of elements Elements create a document tree

Session 6. JavaScript Part 1. Reading

SEEM4570 System Design and Implementation Lecture 04 jquery

Tutorial 10: Programming with JavaScript

Tizen Web UI Technologies (Tizen Ver. 2.3)

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

CISC 1600 Lecture 2.4 Introduction to JavaScript

Lecture : 3. Practical : 2. Course Credit. Tutorial : 0. Total : 5. Course Learning Outcomes

Skyway Builder Web Control Guide

Documents and computation. Introduction to JavaScript. JavaScript vs. Java Applet. Myths. JavaScript. Standard

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

Q1. What is JavaScript?

Chapter 1 Introduction to Computers and the Internet

EECS1012. Net-centric Introduction to Computing. Lecture JavaScript Events

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

Web Site Development with HTML/JavaScrip

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

CERTIFICATE IN WEB PROGRAMMING

Produced by. App Development & Modelling. BSc in Applied Computing. Eamonn de Leastar

Chapter 16. JavaScript 3: Functions Table of Contents

Programmazione Web a.a. 2017/2018 HTML5

JavaScript: More Syntax and Using Events

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

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

COMS W3101: SCRIPTING LANGUAGES: JAVASCRIPT (FALL 2017)

COMS W3101: SCRIPTING LANGUAGES: JAVASCRIPT (FALL 2018)

Document Object Model. Overview

JavaScript s role on the Web

CE212 Web Application Programming Part 2

CHAPTER 6 JAVASCRIPT PART 1

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

Command-driven, event-driven, and web-based software

jquery Tutorial for Beginners: Nothing But the Goods

3Lesson 3: Functions, Methods and Events in JavaScript Objectives

Netscape Introduction to the JavaScript Language

HTML. HTML Evolution

B. V. Patel Institute of Business Management, Computer and Information Technology, UTU. B. C. A (3 rd Semester) Teaching Schedule

Javascript. UNIVERSITY OF MASSACHUSETTS AMHERST CMPSCI 120 Fall 2010

Comprehensive AngularJS Programming (5 Days)

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

Princess Nourah bint Abdulrahman University. Computer Sciences Department

Produced by. App Development & Modelling. Eamonn de Leastar

UI Course HTML: (Html, CSS, JavaScript, JQuery, Bootstrap, AngularJS) Introduction. The World Wide Web (WWW) and history of HTML

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

Introduction to using HTML to design webpages

Working with JavaScript

PHP / MYSQL DURATION: 2 MONTHS

Javascript. Daniel Zappala. CS 360 Internet Programming Brigham Young University

JavaScript Handling Events Page 1

JavaScript CS 4640 Programming Languages for Web Applications

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

CSC Javascript

HTML and JavaScript: Forms and Validation

Mobile Site Development

of numbers, converting into strings, of objects creating, sorting, scrolling images using, sorting, elements of object

INLEDANDE WEBBPROGRAMMERING MED JAVASCRIPT INTRODUCTION TO WEB PROGRAMING USING JAVASCRIPT

Hyperlinks, Tables, Forms and Frameworks

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

LA TROBE UNIVERSITY SEMESTER ONE EXAMINATION PERIOD CAMPUS AW BE BU MI SH ALLOWABLE MATERIALS

CST272 Getting Started Page 1

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

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

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

Scripting. Web Architecture and Information Management [./] Spring 2009 INFO (CCN 42509) Contents

JavaScript: Events, DOM and Attaching Handlers

Produced by. Web Development. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

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

The first sample. What is JavaScript?

CSC309 Midterm Exam Summer 2007

Introduction to HTML5

Module 5 JavaScript, AJAX, and jquery. Module 5. Module 5 Contains 2 components

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

Understanding this structure is pretty straightforward, but nonetheless crucial to working with HTML, CSS, and JavaScript.

JavaScript CS 4640 Programming Languages for Web Applications

JavaScript: Introduction, Types

BSc Applied Computing / Forensics / Entertainment Systems/ IOT. Eamonn de Leastar Dr. Brenda Mullally

Overview. Event Handling. Introduction. Reviewing the load Event. Event mousemove and the event Object. Rollovers with mouseover and mouseout

Produced by. Design Patterns. MSc in Communications Software. Eamonn de Leastar

Transcription:

App Development & Modeling BSc in Applied Computing Produced by Eamonn de Leastar (edeleastar@wit.ie) Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie

Introduction to Javascript

Agenda Nature of Javascript Motivating Example The DOM Script Fragments in Detail: 1.Functions 2.Variables & Operators 3.Date & Time 4.Events 5.Manipulating Lists 3

Agenda Nature of Javascript Motivating Example The DOM Script Fragments in Detail: 1.Functions 2.Variables & Operators 3.Date & Time 4.Events 5.Manipulating Lists 4

Structure of Client-Side Web Markup (HTML) Structure Content Style (CSS) Style Presentation Appearance Function (Javascript) Actions Manipulations 5

Javascript JavaScript provides access to virtually all aspects of a page. CSS properties Markup content Forms, communication to Server JavaScript is a scripting language most often used for client-side web development. It is a dynamic, weakly typed, prototype-based language with first-class functions. JavaScript was influenced by many languages and was designed to have a similar look to Java, but be easier for non-programmers to work with. 6

Javascript & Java: Similarities C-like syntax, the C language being their most immediate common ancestor language. Object-oriented, but with different approaches to classes Sandboxed - i.e. they run inside an all encompassing environment. For Java - the Java Virtual Machine, for Javascript, the Browser Available within browsers (Java requiring a browser plugin) JavaScript was designed with Java's syntax and standard library in mind - all Java keywords were reserved in original JavaScript. JavaScript's standard library follows Java's naming conventions, and JavaScript's Math and Date objects are based on classes from Java 7

Javascript & Java: Differences Static vs Dynamic Typing: Java has static typing - variable must be associated with specific type as soon as they are introduced JavaScript's typing is dynamic - a variable can hold an object of any type and cannot be restricted Functional: JavaScript also has many functional features based on the Scheme language, ultimately derived from the programming language LISP. Object Model Java's objects are class-based; JavaScript's objects are prototype-based. Java is loaded from compiled bytecode; JavaScript is loaded as humanreadable source code. 8

Agenda Nature of Javascript Motivating Example The DOM Script Fragments in Detail: 1.Functions 2.Variables & Operators 3.Date & Time 4.Events 5.Manipulating Lists 9

This pages contains Motivating Example A paragraph 3 <input> elements A Text Field 2 Buttons A list <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>changing the DOM</title> <script type="text/javascript" src="script.js"></script> </head> <body> <p> This page contains a list, which will be modified by pressing the following button: </p> <input type="text" id="itemtext" /> <input type="button" value="add One" onclick="addelementbyid('itemtext')" /> <input type="button" value="clear All" onclick="clearlist()" /> <ol id="list"> <li> An Item </li> </ol> </body> </html> 10

Java Script Functions <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>changing the DOM</title> <script type="text/javascript" src="script.js"></script> </head> <input type="button" value="add One" onclick="addelementbyid('itemtext')" /> <input type="button" value="clear All" onclick="clearlist()" /> The script element identifies a file containing javascript functions The button elements identify the functions + parameters, to be called when the buttons are clicked The functions directly manipulate the DOM, changing the content of the current page function addelementbyid(itemid) { var list = document.getelementbyid('list'); var itemtext = document.getelementbyid(itemid); var newitem = document.createelement('li'); newitem.innerhtml = itemtext.value; list.appendchild(newitem); }! function clearlist() { var list = document.getelementbyid('list'); list.innerhtml = ""; } script.js 11

Example For a static page, clicking on a link/button takes the browser to a new page (new url) With a dynamic page (javascript enabled), clicking on a button may change the current pages structure, content or style 12

Agenda Nature of Javascript Motivating Example The DOM Script Fragments in Detail: 1.Functions 2.Variables & Operators 3.Date & Time 4.Events 5.Manipulating Lists 13

Parsing & Rendering A web browser typically reads and renders HTML documents in two phases: the parsing phase the rendering phase. During the parsing phase, the browser reads the markup in the document, breaks it down into components, and builds a Document Object Model (DOM) tree. The DOM is a in-memory data structure, typically traversed by Java Script code 14

DOM Tree Each object in the DOM tree is called a node. There are several types of nodes, including element nodes and text nodes. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"! "http://www.w3.org/tr/html4/strict.dtd">! <html>! <head>! <title>widgets</title>! </head>! <body>! <h1>widgets</h1>! <p>welcome to Widgets, the number one company! in the world for selling widgets!</p>! </body>! </html> At the top of the tree is a document node, which contains an element node called the root node; this is always the html element in HTML documents. It branches into two child element nodes head and body which then branch into other children. function clearlist() { var list = document.getelementbyid('list'); list.innerhtml = ""; } 15

DOM Manipulation All aspects of the DOM - essentially a structured version of the html + the CSS loaded in the current page, can be accessed in javascript via the document object. If a script changes the DOM, the effects are immediately visible in the rendered document in the browser 16

Agenda Nature of Javascript Motivating Example The DOM Script Fragments in Detail: 1.Functions 2.Variables & Operators 3.Date & Time 4.Events 5.Manipulating Lists 17

Script Location Where a script can be provided, 3 options available External Script <script src="script.js" type="text/javascript" > </script>! Script within HTML document! "Inline" scripts as values of event attributes <script type="text/javascript"> /* JavaScript code as content of script element */ </script> <a href="#" onclick="window.resizeto(800,600))"> Size Window to 800 x 600 </a> 18

Functions 1 Functions are equivalent to methods in Java Introduced by the function keyword, and then scoped by { and } function message1() { document.write ("Hello World"); }! function message2() { document.write ("Hello World Again"); } These two functions write strings to the current document - the DOM There effect on the DOM depends on whether is page is currently loading, or has already loaded 19

Functions 2 These three functions display dialog boxes on top of the browser function showalert() { alert("hello! I am an alert box!"); }! function showconfirm() { confirm("press a button"); }! function showprompt() { prompt("please Enter your Name:", "none"); } 20

Functions 3 Functions can perform computations, implement algorithms or arbitrary complexity function calcageinsecs (age) { var age = prompt("please Enter your age in years:", "0"); var seconds = age * 365 * 24 * 60 * 60; alert("you have lived " + seconds + " seconds!"); } 21

Variables JavaScript variables have some similarities to variables you have already encountered in the Java programming language They have names, like x, or a more descriptive name, like ageinsecs. The variable names are case sensitive (y and Y are two different variables) They must begin with a letter or the underscore character The differ from Java variables in a number of important ways there is no "type" associated with the variable The variables can hold numbers, strings, boolean values (true,false) or null The same variable can, at different times, hold different values, and different type (a number or a string for instance). Variables are always introduced with the "var" keyword var x=5;! var dvdname ="The Crazies";! var valid = false;! var go = true;! var cost = 23.99; 22

Arithmetic Operators Assume y contains 5 23

Assignment Operators Assume x is 10 and y is 5 24

Comparison & Logical Operators Assume x contains 5 25

Date & Time The Date object is useful when you want to display a date or use a timestamp in some sort of calculation. In Javascript, you can either make a Date object by supplying the date of your choice, or you can let JavaScript create a Date object based on the system clock function getdate() { var currenttime = new Date(); var month = currenttime.getmonth(); var day = currenttime.getdate(); var year = currenttime.getfullyear(); var date = month + "/" + day + "/" + year; return date; } function gettime() { var currenttime = new Date(); var hours = currenttime.gethours(); var minutes = currenttime.getminutes(); var seconds = currenttime.getseconds(); var time = hours + ":" + minutes + ":" + seconds; return time; } <body> <p> The current Date is </p> <script type="text/javascript"> document.write(getdate()); </script> <p> Did you see the Date? </p> </body> 26

Events An event is some activity, usually initiated by the user, which can be detected and intercepted by the browser. Very often associated with the input device (keyboard or mouse) But may also be associated with other activities - e.g. a page load click change submit load mouseout mouseover blur focus dblclick keydown keyup keypress unload mousedown mousemove mouseup reset select 27

Input Element One of the most diverse elements in html. Many Types possible <input type="button" value="click Me" /> button text checkbox <input type="text" value="click Me" /> radio password etc Will often define and participate in events 28

onclick for Input Button <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <script type="text/javascript" src="script4.js"> </script> <title>insert title here</title> </head> <body> <p> About to launch a script: </p> <script type="text/javascript"> document.write("hello World") </script> <p> Script has finished - did you see the text? </p> <input type="button" value="click Me" onclick="calcageinsecs()" /> </body> </html> function calcageinsecs (age) { var age = prompt("please Enter your age in years:", "0"); var seconds = age * 365 * 24 * 60 * 60; alert("you have lived " + seconds + " seconds!"); } 29

onclick for Input Button <head> //... <script type="text/javascript" src="script.js"> </script> //... </head> <body> //... <input type="button" value="click Me" onclick="calcageinsecs()" /> </body> function calcageinsecs (age) { var age = prompt("please Enter your age in years:", "0"); var seconds = age * 365 * 24 * 60 * 60; alert("you have lived " + seconds + " seconds!"); } script.js 30

Changing Styles <body id="homepage"> <h1 id="title"> This is a title </h1> <p> Changing the styles </p> <input type="button" value="make body red" onclick="changebackground('homepage', 'red')" /> <input type="button" value="make headding green" onclick="changebackground('title', 'green')" /> </body> changebackground() is method we have written, taking two parameters Parameter 1: the Id of an element whose colour you wish to change Parameter 2: the new colour for the background of the element 31

function changebackground() function changebackground(id, colour) { var element = document.getelementbyid(id); element.style.backgroundcolor = colour; } Two statements in the function: Statement 1: ask the document (the DOM) for a reference to the element with a specific id. Store this in the variable called element Statement 2: reach into this element, get its current style, and change the background colour to the one specified by the parameter 32

<body id="homepage"> <h1 id="title"> This is a title </h1> <p> Changing the styles </p> <input type="text" id="bodycolour" /> <input type="button" value="make body this colour" onclick="changebackgroundbyid('homepage', 'bodycolour')" /> <input type="text" id="headercolour" /> <input type="button" value="make headding this colour" onclick="changebackgroundbyid('title', 'headercolour')" /> </body> Specify any valid colour in text fields changebackgroundbyid() reads the colour from the text fields, and sets the style accordingly 33

changebackgroundbyid() function changebackgroundbyid(elementid, colourtextid) { var element = document.getelementbyid(elementid); var colour = document.getelementbyid(colourtextid); element.style.backgroundcolor = colour.value; } Get reference to the element to the changed Get a reference to the text field containing the colour Set the element s colour to the colour in that text field 34

Manipulating Lists <body> <p> This page contains a list, which will be modified by pressing the following buttons: </p> <input type="button" value="add One" onclick="addelement('one')" /> <input type="button" value="clear All" onclick="clearlist()" /> <ol id="list"> <li> An Item </li> </ol> </body> 35

functions addelement(), clearlist() function addelement(item) { var list = document.getelementbyid('list'); var newitem = document.createelement('li'); newitem.innerhtml = item; list.appendchild(newitem); }! function clearlist() { var list = document.getelementbyid('list'); list.innerhtml = ""; } document.createelement will create a new element appendchild will attach an new element to an existing element innerhtml is a simple mechanism for changing the contents of an element 36

addelementbyid <input type="text" id="itemtext" /> <input type="button" value="add One" onclick="addelementbyid('itemtext')" /> <input type="button" value="clear All" onclick="clearlist()" /> <ol id="list"> <li> An Item </li> </ol> Retrieve text from text field, and add to list 37

Function addelementbyid() function addelementbyid(itemid) { var list = document.getelementbyid('list'); var itemtext = document.getelementbyid(itemid); var newitem = document.createelement('li'); newitem.innerhtml = itemtext.value; list.appendchild(newitem); } 1.Retrieve reference to the list 2.Retrieve reference to the text field 3.Create a new list item element 4.Insert the text in the text field into this new list item element 5.Append this new element into the list 38

Except where otherwise noted, this content is licensed under a Creative Commons Attribution-NonCommercial 3.0 License.! For more information, please see http:// creativecommons.org/licenses/by-nc/3.0/