Download presentation
Presentation is loading. Please wait.
1
JavaScript Intro
2
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
3
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
4
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*/
5
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
6
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
7
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
8
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
9
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
10
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)
11
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
12
Functions These are codes that are not executed until they are referenced or called. An example is the alert() function we’ve been using
13
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
14
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
15
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
16
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
17
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
18
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
19
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
20
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);
21
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”;
22
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’]
23
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);
24
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;
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.