JavaScript Intro.

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

JavaScript and the DOM Les Carr COMP3001 Les Carr COMP3001.
The Web Warrior Guide to Web Design Technologies
Computer Science 103 Chapter 4 Advanced JavaScript.
CNIT 133 Interactive Web Pags – JavaScript and AJAX Event and Event Handling.
WEEK 3 AND 4 USING CLIENT-SIDE SCRIPTS TO ENHANCE WEB APPLICATIONS.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
CSS Class 7 Add JavaScript to your page Add event handlers Validate a form Open a new window Hide and show elements Swap images Debug JavaScript.
Javascript. Outline Introduction Fundamental of JavaScript Javascript events management DOM and Dynamic HTML (DHTML)
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
Using Client-Side Scripts to Enhance Web Applications 1.
Intro to JavaScript Scripting language –ECMAScript compliant –Client side vs. server side Syntactic rules –White space –Statement end: ; optional –Comments:
JavaScript - Basic Concepts Prepared and Presented by Hienvinh Nguyen, Afshin Tiraie.
Scott Marino MSMIS Summer Session Web Site Design and Authoring Session 8 Scott Marino.
ECA 225 Applied Interactive Programming1 ECA 225 Applied Online Programming basics.
Event JavaScript's interaction with HTML is handled through events that occur when the user or browser manipulates a page. When the page loads, that is.
Chapter 2: Variables, Functions, Objects, and Events JavaScript - Introductory.
05 – Java Script (1) Informatics Department Parahyangan Catholic University.
JavaScript, Fourth Edition
1 Chapter 3 – JavaScript Outline Introduction Flowcharts Control Structures if Selection Structure if/else Selection Structure while Repetition Structure.
4. Javascript M. Udin Harun Al Rasyid, S.Kom, Ph.D Lab Jaringan Komputer (C-307) Desain.
Jaana Holvikivi 1 Introduction to Javascript Jaana Holvikivi Metropolia.
IS2802 Introduction to Multimedia Applications for Business Lecture 3: JavaScript and Functions Rob Gleasure
1 CSC160 Chapter 7: Events and Event Handlers. 2 Outline Event and event handlers onClick event handler onMouseOver event handler onMouseOut event handler.
Making dynamic pages with javascript Lecture 1. Java script java versus javascript Javascript is a scripting language that will allow you to add real.
Project 8: Reacting to Events Essentials for Design JavaScript Level One Michael Brooks.
Web Programming Java Script & jQuery Web Programming.
7. JavaScript Events. 2 Motto: Do you think I can listen all day to such stuff? –Lewis Carroll.
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.
CGS 3066: Web Programming and Design Spring 2016 Programming in JavaScript.
JavaScript Events Java 4 Understanding Events Events add interactivity between the web page and the user You can think of an event as a trigger that.
JavaScript and Ajax (JavaScript Environment) Week 6 Web site:
JavaScript Events. Understanding Events Events add interactivity between the web page and the user Events add interactivity between the web page and the.
Introduction to JavaScript Events Instructor: Sergey Goldman 1.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
 2001 Prentice Hall, Inc. All rights reserved. Outline 1 JavaScript.
SE-2840 Dr. Mark L. Hornick 1 Dynamic HTML Handling events from DOM objects.
Java Script Introduction. Java Script Introduction.
JavaScript and HTML Simple Event Handling 11-May-18.
Unit M Programming Web Pages with
Chapter 6 JavaScript: Introduction to Scripting
JavaScript is a programming language designed for Web pages.
Introduction to JavaScript Events
Unit M Programming Web Pages with
Project 9 Creating Pop-up Windows, Adding Scrolling Messages, and Validating Forms.
JavaScript Functions.
JavaScript Fundamentals
4. Javascript Pemrograman Web I Program Studi Teknik Informatika
Week#2 Day#1 Java Script Course
14 A Brief Look at JavaScript and jQuery.
JavaScript and HTML Simple Event Handling 19-Sep-18.
JavaScript Events.
Objectives Insert a script element Write JavaScript comments
Your 1st Programming Assignment
WEB PROGRAMMING JavaScript.
The Internet 12/8/11 JavaScript Review
PHP.
T. Jumana Abu Shmais – AOU - Riyadh
Functions, Regular expressions and Events
JavaScript CS 4640 Programming Languages for Web Applications
JavaScript Basics What is JavaScript?
JavaScript: Introduction to Scripting
JavaScript and Ajax (JavaScript Events)
Web Programming and Design
Web Programming and Design
JavaScript and HTML Simple Event Handling 26-Aug-19.
JavaScript CS 4640 Programming Languages for Web Applications
JavaScript and HTML Simple Event Handling 4-Oct-19.
CGS 3066: Web Programming and Design Fall 2019
Presentation transcript:

JavaScript Intro

Intro What it is What can it do Dynamic loosely typed scripting language What can it do Introduce interactivity Manipulate the Document Object Model (DOM) Alter contents of a page or CSS styles Form validation

Adding JavaScript to a Page Embedded directly in HTML document <script> //JavaScript code here </script> Using an external file <script src=‘myScript.js’></script> Script can be placed anywhere in document, preferably placed just before the closing body tag

The Basics JavaScript (JS) is case sensitive Whitespaces like tabs spaces are ignored unless part of a string Semi colon is optional at the end of a statement, but it is good practice //Single line comment /*Multi-line comment*/

Basics alert(‘Hello’); confirm(‘Are you sure’); prompt(‘How are you’); Displays a dialog box with the parameter, ‘Hello’ in this case, as the message confirm(‘Are you sure’); Displays dialog box with message and Ok/Cancel prompt(‘How are you’); Displays dialog box with text field for user input

Variables These are information containers. You name one and assign it a value. var foo = 3; Notes: var keyword optional (sort of) Use Descriptive variable names; names start with a letter or an underscore; contains letters, digits and underscores; no space

Data Types Undefined: A variable that is declared but is not initialized var foo; alert(foo);//undefined Null: a declared variable with no inherent value var foo=null; alert(null);//null (case sensitive) Numbers: Positive and negative integers and floating point numbers Strings: Sequence of characters and or numbers enclosed in quotes var foo = “hello”; alert(foo)//hello + serves as string concatenation: alert(foo+foo)//hellohello var foo = “4”; alert(foo+foo) //??? var foo = “One”; alert(foo+1)//??? Boolean: true or false used in implementing logic var foo = true; //No quotes necessary Arrays: Group of values assigned to one variable. Arrays are indexed with the first element having index 0 var foo = [“hello”, 4,”four”]; alert(foo[0]);//”hello” alert(foo[2]);//four

Comparison Operators == Is equal to != Is not equal to ===  Is identical to (equal to and of the same data type) !==  Is not identical to > Is greater than >= Is greater than or equal to < Is less than <= Is less than or equal to

Mathematical Operators + Addition between numerical values - Subtraction * Multiplication += Adds the value to itself ++ Increases the value of a number (or a variable containing a number value) by 1 -- Decreases the value of a number (or a variable containing a numbervalue) by 1

If/else Statements Implementing logic and decisions if ( condition){ //Statement to execute when true } else{ //Statements to execute when false Note: We can test conditions on members of an array; if(foo[0]==1)

Loops Mechanisms for repeated execution of instructions. Best used in processing large data sets like arrays for (initialization; condition; increment){ //Statements to execute here } Other looping mechanisms exist. Find them Example: Loop through an array and display its members Loops can be nested for interesting effects Looping through a list of elements on the page and checking the value of each, applying a style to each, or adding/removing/changing an attribute on each. For example, we could loop through each element in a form and ensure that users have entered a valid value for each before they proceed. • Creating a new array of items in an original array that have a certain value. We check the value of each item in the original array within the loop, and if the value matches the one we’re looking for, we populate a new array with only those items. This turns the loop into a filter, of sorts

Functions These are codes that are not executed until they are referenced or called. An example is the alert() function we’ve been using

Native Functions Functions predefined in JavaScript alert(), confirm(), and prompt() Show dialog boxes Date() Shows current date parseInt(“4”) Converts a string of numbers to Number data type setTimeout(functionName, 1000) Executes the function with the same name as the first argument after a delay, the delay is specified as the second argument

Custom Functions Start with function keyword followed by a name for the function, followed by opening and closing parentheses, followed by opening and closing curly brackets -Anonymous Functions have no name function foo(){ alert(“CALLED!”);//Only when foo() is called } Write once execute many times. Saves time and redundant coding

Arguments Pass data to functions to apply logic to different data sets Add one or more comma-separated variables in the parentheses at the time the function is defined When we call that function, anything we include between the parentheses will be passed into that variable as the function executes Results of functions can be passed back to caller using return keyword function sum(a,b){ return a+b; } var tmp = sum(3,5); alert(tmp); //8 Execution in a function stops when return keyword is encountered. Any code found after return is ignored

Variable Scope The availability of a variable inside or outside a function defines its scope Global variables are available anywhere in the script. Variables defined outside a function are global variables Local variables are only available in their parent functions Variables defined in a function can be global or local. Add the var keyword to their definition to make them local and omit the var keyword to make them global function double( num ){ total = num + num; return total; } var total = 10; var number = double( 20 ); alert( total ); //40 To avoid variable collision, always try to use local variables

The Browser Object Browser can be manipulated using the window object. The window object is a collection of properties and functions (like alert()) event Represents the state of an event history Contains the URLs the user has visited within a browser window location Gives read/write access to the URI in the address bar status Sets or returns the text in the status bar of the window alert() Displays an alert box with a specified message and an OK button close() Closes the current window confirm() Displays a dialog box with a specified message and an OK and a Cancel button focus() Sets focus on the current window

Events An event is an action that can be detected with JavaScript, such as when the document loads or when the user clicks on an element or just moves her mouse over it. In scripts, an event is identified by an event handler. For example, the onload event handler triggers a script when the document loads, and the onclick and onmouseover handlers trigger a script when the user clicks or mouses over an element, respectively

Events onblur An element loses focus onchange The content of a form field changes onclick The mouse clicks an object onerror An error occurs when the document or an image loads onfocus An element gets focus onkeydown A key on the keyboard is pressed onkeypress A key on the keyboard is pressed or held down onkeyup A key on the keyboard is released onload A page or an image is finished loading onmousedown A mouse button is pressed onmousemove The mouse is moved onmouseout The mouse is moved off an element onmouseover The mouse is moved over an element onmouseup A mouse button is released onsubmit The submit button is clicked in a form

Applying Event Handlers • As an HTML attribute <body onclick="myFunction();"> /* myFunction will now run when the user clicks anything within 'body' */ Bad, why? • As a method attached to the element window.onclick = myFunction; /* myFunction will run when the user clicks anything within the browser window */ window.onclick = myFunction; window.onclick = myOtherFunction;//overwrites first binding • Using addEventListener (Recommended method) The syntax is a bit more verbose. We start by calling the addEventListener method of the target object, and then specify the event in question and the function to be executed as two arguments. window.addEventListener("click", myFunction);

Objects Objects are entities with properties Can be accessed with dot notation objectName.property Define a property by assigning it a value var car = new Object(); car.make = “Ford”; car.model=“Focus”; To reference properties alert(car.make);//Ford alert(car.color);//undefined Properties can also be referenced using square brackets notation car[‘make’]=“Toyota”;

Creating new Objects Using Object Initializer var obj = { property_1: value_1, // property_# may be an identifier... 2: value_2, // or a number... // ..., 'property n': value_n }; // or a string Using a constructor function: To define an object type, create a function for the object type that specifies its name, properties, and methods function Car(make, model, year) { this.make = make; this.model = model; this.year = year; } You can now create any number of objects of type Car var mycar = new Car('Eagle', 'Talon TSi', 1993);//myCar[‘make’]

Inheritance Objects can inherit properties from other objects (No classes) Every object has a prototype property that points to its parent (Object highest object in heirarchy) Data and Functions (methods) can be inherited Inherit properties using Object.create(parentObject);

Example example( strings ) { var tmp = strings[0]; for( i = 1; i < strings.length; i++ ) { if ( strings[i].length > tmp.length ) { tmp = strings[i]; } return tmp;