Intro to javascript dom
Download
1 / 76

Intro to Javascript & DOM - PowerPoint PPT Presentation


  • 210 Views
  • Uploaded on

Intro to Javascript & DOM. Javascript Outline. Introduction Variables & data types Control Statements Arrays Functions Objects. Javascript Quick facts. Netscape was battling with IE and wanted a lightweight component to compete with Microsoft VB.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about ' Intro to Javascript & DOM' - bess


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

Javascript outline
Javascript Outline

  • Introduction

  • Variables & data types

  • Control Statements

  • Arrays

  • Functions

  • Objects


Javascript quick facts
Javascript Quick facts

  • Netscape was battling with IE and wanted a lightweight component to compete with Microsoft VB.

  • Created by Brendan Eich(creator of mozillafoundation)in 1995 while at Netscape.

CSE 3345


Javascript quick facts1
Javascript Quick facts

  • Javascript was described by Brendan as, “something that had to ‘look like Java’ only less so and be Java’s dumb kid brother or boy-hostage sidekick.”

  • Had to be created in 10 days, or something worse would have been developed.

CSE 3345


Javascript disclaimer
Javascript Disclaimer

  • A lot of people hate javascript!

  • A lot of the people that hate javascript really just don’t understand it.

  • There are good parts and bad parts.

CSE 3345


3 ways use js
3 Ways Use JS

  • Inline

  • Embedded

  • External

CSE 3345


Inline example
Inline Example

<div onclick="alert('this is a horrible idea');">

Click me

</div>

CSE 3345


Embedded example
Embedded Example

<html>

<head>

<scripttype="text/javascript">

window.onload=function(){ alert('window loaded');};

</script>

</head>

</html>

CSE 3345


External example
External Example

index.html

<html>

<head>

<!-- Make sure you always use an opening and closing <script> tag;

else your script might not load -->

<scripttype="text/javascript"src="test.js"></script>

</head>

</html>

test.js

window.onload=function(){ alert('window loaded');};

CSE 3345


Same as css
Same as CSS

  • Reasons to use each method are the same as CSS.

  • External is preferred!

CSE 3345


Js characteristics
JS characteristics

  • It is a dynamic and weakly typed language.

  • Dynamic type means that there are no compile time checks to deduce variable type and type conversions.

  • Weakly typed mean the language will figure out for itself how to convert variables of different type.

CSE 3345


Strongly t yped example
Strongly Typed Example

Test.java:

publicclass Test {

publicstaticvoid main(String args[]){

String x ="2";

intnum=7;

num+= x;// Integer.parseInt(x);

System.out.println(num);

}

}

Test.java:6: error: inconvertible types

num += x;// Integer.parseInt(x);

^

required: int

found: String

1 error

CSE 3345


Weakly typed example
Weakly Typed Example

var x ="2";

varnum=7;

num+= x;

console.log(num);//72

CSE 3345


Outputting text to the console
Outputting text to the console

  • The web console provides a heads up display for the web by letting users see error messages and other logged information.

  • console.log() – Outputs a message to the web console. Extremely useful for debugging!


Outputting text to the console1
Outputting text to the console

Print strings

console.log(“Hello “ + “world!”);

Print objects

var foo = ‘hello’;

var bar = 0x01;

console.log(foo + “ “ + bar + “!”);


Javascript outline1
Javascript Outline

  • Introduction

  • Variables & data types

  • Control Statements

  • Arrays

  • Functions

  • Objects


Declaring variables
Declaring variables

  • Variables are declared using the var keyword.

  • Javascript does not allow variables to be declared with a specific type (int, float, boolean, etc).

  • Javascript does have different data types


Javascript types
Javascript types

typeof4;// number

typeof0xFF;// number

typeofx;// undefined

typeoftrue;// boolean

typeof"String";// string

typeof{};// object

typeof[];// object

typeoffunction(){ alert("hi!");};// function


To var or not to var
To var, or not to var?

  • Any variable declared without the varkeyword becomes a global variable.

  • That means un-varred variables in methods automatically are global.

CSE 3345


Truthy and falsy values
Truthy and falsy values

Any value can be converted to a boolean according to the following rules:

  • false, 0, the empty string (“”), NaN, null, and undefined all become false.

  • All other values become true.

CSE 3345


Truth and falsy in action
Truth and Falsy in Action

var c =(false==0);// true

var d =(false=="");// true

var e =(0=="");// true

//null and undefined are only equal to themselves and each other

var f =(null ==false);// false

var g =(null == null);// true

var h =(undefined == undefined);// true

vari=(undefined == null);// true

//NaN is not equivalent to anything

var j =(NaN == null);// false

var k =(NaN == NaN);// false

CSE 3345


Comparing for equality
Comparing for equality

  • The Equals operator is ==. Compares “truthy” and “falsy” values of variables.

  • Strict equals operator is ===. Always returns false when the operands are of different types.

CSE 3345


Always use
Always use ===

  • To avoid unintended results, always use the strict equals operator.

CSE 3345


String operators
String operators

  • Use the + operator to concatenate two strings together.

    var x = “hello” + “ world”;

  • Use the += operators to append two existing strings.

    var x = “hello”;

    x += “ world”;

CSE 3345


Converting strings to numbers
Converting strings to numbers

  • parseInt() – parses a string object and returns an integer of the specified radix or base. You should always specify a base.

    • parseInt(“010”, 2);// 2

    • parseInt(“010”, 10); // 10

  • parseFloat() – parses a string object and returns a floating point number. Always uses base 10.

    • parseFloat(“10.44”); //10.44

CSE 3345


Converting strings to numbers1
Converting strings to numbers

  • You can also prepend a string with a + to convert the string to a number.

    varstring="50";

    console.log(string+100);// 50100

    console.log(+string+100);// 150

CSE 3345


Javascript outline2
Javascript Outline

  • Introduction

  • Variables & data types

  • Control Statements

  • Arrays

  • Functions

  • Objects


Control statements
Control Statements

  • Javascript supports the typical list of control statements.

  • if, else, else if

  • while

  • do while

  • for

  • switch

  • break

  • continue

CSE 3345


Control statements1
Control Statements

  • In addition to that list, js has a “for in” statement.

  • Use it to iterate over properties of an object.

  • Be careful using “for in” for arrays. Sometimes an object will have properties that you’re unaware and give weird output.

CSE 3345


For in example
For in example

// Initialize object.

a = {"a" : "Athens" , "b" : "Belgrade", "c" : "Cairo"} ;

// Iterate over the properties.

vars = "“;

for(var key in a) {

s += key + ": " + a[key];

s += "<br />";

}

document.write(s); // Output:// a: Athens// b: Belgrade// c: Cairo

CSE 3345


Bad part of javascript
Bad Part of Javascript

  • Always place an opening brace “{“ on the same line as the control statement or function.

  • Undesired results can occur if you don’t follow this practice.

  • See here for details

CSE 3345


Javascript outline3
Javascript Outline

  • Introduction

  • Variables & data types

  • Control Statements

  • Arrays

  • Functions

  • Objects


Arrays
Arrays

  • Arrays are a special type of object that have a length property.

  • Accessing a value that is outside of the array bounds returns undefined.

  • The length property returns the length of the array.

  • The length is also one more than the highest index.

  • The length of an array isn’t always the number of items in the array.

CSE 3345


Array length bad part
Array Length Bad Part

var x =["dog","cat","monkey"];

x.length;//3

x[100]="aligator";

x.length;//101

CSE 3345


Bad array initialization
Bad Array Initialization

> var a = new Array();

> a[0] = "dog";

> a[1] = "cat";

> a[2] = "hen";

> a.length

3

> var a = new Array(); //bad

CSE 3345


Good array initialization
Good Array Initialization

> var a = ["dog", "cat", "hen"];

> a.length

3

> var a = []; //good

CSE 3345


Array methods
Array Methods

CSE 3345


Javascript outline4
Javascript Outline

  • Introduction

  • Variables & data types

  • Control Statements

  • Arrays

  • Functions

  • Objects


Functions
Functions

  • Almost like typical C/C++ and Java functions, except you don’t specify a return type.

    function sayHello() {

    alert(“hello world!”);

    }

CSE 3345


Function with parameters
Function with parameters

  • Once again similar to C/C++ and Java, but you don’t specify the data type of the parameters.

  • You also don’t prefix the parameter name with the var keyword.

    function add(x, y) {

    return x + y;

    }

CSE 3345


The arguments object
The arguments object

  • The arguments object is a local variable available within all functions that contains an entry for each argument passed to a function.

  • The arguments object will also hold values for parameters that are specified by the function.

CSE 3345


Arguments object example
Arguments object example

functionconcat(parm1){

varstr= parm1;

for(vari=0,len=arguments.length;i<len;i++){

str+=" "+ arguments[i];

}

returnstr;

}

concat("1","2","3","4"); //"1 1 2 3 4”

CSE 3345


Anonymous function
Anonymous Function

  • You can create functions that are not bounded to an identifier.

    alert((function(){return "hello";})());

CSE 3345


Functions are first class objects
Functions are first class objects

  • This means that javascript functions are just a special type of object that can do all things regular objects can do.

    This allows

  • Functions to be stored as variables

  • Functions to be passed as a parameter to another function.

  • You can return a function from another function.

CSE 3345


Functions stored as variables
Functions stored as variables

functionsayHi(){console.log(“hi”);}

var hi =sayHi;

hi();// hi

  • Note that when assigning a function to a variable, you don’t place “()” after the function name.

  • However, to execute the function with the variable name, you must use “()”.

CSE 3345


Function as a parameter of another function
Function as a parameter of another function

functionsayHi(){return"hi";}

functionsalutation(greeting, name){

console.log(greeting()+" "+ name);

}

varhi =sayHi;

salutation(hi,"Fred"); // hi Fred

CSE 3345


Function as a return value for another function
Function as a return value for another function

functionadd(x,y){return x + y;}

functionsubtract(x,y){return x - y;}

functiongetOperation(x){

var operation = x %2===0? add : subtract;

return operation;

}

var operation =getOperation(2);

operation(5,3);// 8

CSE 3345


Javascript outline5
Javascript Outline

  • Introduction

  • Variables & data types

  • Control Statements

  • Arrays

  • Functions

  • Objects


Objects
Objects

  • Objects are a collection of name-value pairs

  • The “name” part is a javascript string.

  • The “value” part can be any javascript value.

CSE 3345


Creating objects
Creating Objects

var student ={

name:"Wade Wilson",

alias:"wwilson",

id:12345678,

email:"[email protected]",

isPassing:true

};

CSE 3345


Object member variables are public
Object member variables are public

There are no access level modifiers (public, protected, private) to prevent access to an object’s variables.

student.name;//"Wade Wilson"

student.alias;//"wwilson"

student.id;//12345678

student.email;//"[email protected]"

student.isPassing;//true

CSE 3345


Object member variables are public1
Object member variables are public

Using the object literal syntax, we can access variables a second way.

student["name"];//"Wade Wilson"

student["alias"];//"wwilson"

student["id"];//12345678

student["email"];//"[email protected]"

student["isPassing"];//true

This approach makes it possible to calculate the member variable at run-time with a dynamic string.

CSE 3345


Object methods
Object Methods

var student ={

name:"Wade Wilson",

alias:"wwilson",

id:12345678,

email:"[email protected]",

isPassing:true,

sayHi:function(){console.log("hi");}

};

student.sayHi(); //”hi”

CSE 3345


Your turn
Your turn

Create a function to print each pattern

**********************

**********************

**********************

**********************

**********************

**********************

**********************

**********************

**********************

**********************

CSE 3345



  • Intro to javascript

  • DOM

    • About

    • Tree / nodes

    • Accessing elements

    • Creating elements

    • Deleting element


Quick facts
Quick facts

  • DOM – document object model

  • Is a cross-platform language agnostic convention for representing HTML, XHTML, and XML documents.

  • Think of the DOM as a family tree which represents a document.

  • The DOM represents the document as a structured group of nodes/objects that have properties and methods.


Html to dom tree
HTML to DOM Tree

<html>

<head><title>DOM Test</title></head>

<body>

<pclass="text"style="color:red">I am some text.</p>

</body>

</html>

HTML

HEAD

BODY

TITLE

P

class: text

style

color: red

CSE 3345


Html to dom tree1
HTML to DOM Tree

document

HTML

HEAD

BODY

TITLE

P

class: text

style

color: red

CSE 3345


Live dom viewer
Live DOM Viewer

  • Visit the Live DOM Viewer to see the DOM in action.

CSE 3345


Dom api
DOM API

  • API – application programming interface

  • Provides capabilities to change a document’s structure, style, and content.

  • In the DOM, everything in the document becomes nodes (elements, text, attributes, comments, etc) and forms a node tree.

CSE 3345


Getting access to the dom from js
Getting access to the DOM from JS

  • Each webpage loaded in the browser has its own document object.

  • The document object serves as the entry point to the web page’s content aka the DOM tree.

CSE 3345


How to access the dom in js
How to access the DOM in js

//javascriptcode

//this returns an array of all the div elements in //the HTML document.

vardivs = document.getElementsByTagName("div");

CSE 3345


Dom api1
DOM API

  • Allows developers to access nodes in the DOM Tree.

  • Each node is actually a javascript object.

  • Therefore, each object can have properties and methods

CSE 3345


A few dom traversing m ethods
A few DOM traversing methods

  • getElementByID(id) – get the element with the specified id or null if an element wasn’t found.

  • getElementsByTagName(tag) – returns an array of all elements with the specified tag.

  • getElementsByClassName(class) – returns an array of all elements which have the given class name.

CSE 3345


Node properties
Node Properties

document

HTML

HEAD

BODY

TITLE

P

class: text

style

color: red

CSE 3345


A few node properties
A few node Properties

  • innerHTML– the textual value of the node

  • nodeName– the name of the node

  • nodeValue – the value of the node

  • parentNode - the parent node of the node

  • childNodes – the child nodes of the node

  • attributes – the attributes of the node

  • firstChild – the first child of the node

  • nextSibling- the next sibling of the node

CSE 3345


Nodevalue
nodeValue

  • nodeValue can return different things depending on what the node is

  • Attribute – the value will be the value of the attribute.

  • Text – the value will be the text content

  • Element – the value will be null

CSE 3345


Node trees
Node Trees

  • All nodes in the tree can be accessed and their contents can be modified or deleted.

  • New nodes can be created and inserted into the tree.

CSE 3345


Dom manipulation methods
DOM manipulation methods

  • removeChild(node) – remove a child node from the current node.

  • createElement(element) – create an element node of the specified type.

  • appendChild(node) – insert a child node to the current node.

  • setAttribute(name, value) – set a new attribute with the specified name and value to this node.

CSE 3345


Using the dom api
Using the DOM API

  • We can navigate to any section of the DOM tree by using properties.

    • firstChild

    • lastChild

    • nextSibling

    • previousSibling

  • Once we’ve found the node we want, we can set almost any HTML attribute or data attribute and CSS property.

CSE 3345


Using dom to change html
Using DOM to change HTML

  • Use the properties of each node to change specific things

    • innerHTML

    • setAttribute()

CSE 3345


Using dom to change css
Using DOM to change CSS

  • Each element node has a style property.

  • Using style, you change specific CSS properties for the element’s inline style.

  • Note this will not fetch CSS from embedded or external declarations.

CSE 3345


Dom css example
DOM CSS Example

//changes the body element's inline color style to be red

document.body.style.color="red";

CSE 3345


Dom references
DOM References

  • Sitepoint

  • Use the intellisense feature of Chrome Web Inspector to find available methods and properties.

CSE 3345


Dom example
DOM Example

http://cssdeck.com/labs/collab/knejnp4j/0

http://jsfiddle.net/blinkmacalahan/vfVM6/6/

CSE 3345


ad