+ All Categories
Home > Documents > Javascript DHTML

Javascript DHTML

Date post: 03-Nov-2014
Category:
Upload: sanket-doshi
View: 156 times
Download: 0 times
Share this document with a friend
Description:
jsp
Popular Tags:
39
Introduction to DHTML Introduction to DHTML DHTML is NOT a language. DHTML stands for Dynamic DHTML is NOT a language. DHTML stands for Dynamic HTML. HTML. DHTML is a TERM describing the art of making DHTML is a TERM describing the art of making dynamic and interactive web pages. dynamic and interactive web pages. DHTML combines HTML, JavaScript, DOM, and CSS. DHTML combines HTML, JavaScript, DOM, and CSS. DHTML Technologies are : DHTML Technologies are : HTML 4 HTML 4 Javascript Javascript HTML Document Object Model (DOM) HTML Document Object Model (DOM) CSS CSS
Transcript
Page 1: Javascript DHTML

Introduction to DHTMLIntroduction to DHTML

DHTML is NOT a language. DHTML stands for Dynamic HTML.DHTML is NOT a language. DHTML stands for Dynamic HTML. DHTML is a TERM describing the art of making dynamic and DHTML is a TERM describing the art of making dynamic and

interactive web pages.interactive web pages. DHTML combines HTML, JavaScript, DOM, and CSS.DHTML combines HTML, JavaScript, DOM, and CSS.

DHTML Technologies are :DHTML Technologies are :– HTML 4HTML 4

– JavascriptJavascript

– HTML Document Object Model (DOM)HTML Document Object Model (DOM)

– CSSCSS

Page 2: Javascript DHTML

HTML 4 and JavascriptHTML 4 and Javascript

HTML 4HTML 4

The W3C HTML 4 standard has rich support for dynamic content: The W3C HTML 4 standard has rich support for dynamic content: HTML supports JavaScript HTML supports JavaScript HTML supports the Document Object Model (HTML supports the Document Object Model (DOMDOM) ) HTML supports HTML Events HTML supports HTML Events HTML supports Cascading Style Sheets (HTML supports Cascading Style Sheets (CSSCSS) )

JavaScriptJavaScript

JavaScript is the scripting standard for HTML.JavaScript is the scripting standard for HTML. DHTML is about using JavaScript to control, access and manipulate DHTML is about using JavaScript to control, access and manipulate

HTML elements.HTML elements.

Page 3: Javascript DHTML

HTML DOMHTML DOM

The HTML DOM is the W3C standard The HTML DOM is the W3C standard Document Object ModelDocument Object Model for for HTML.HTML.

The HTML DOM defines a standard set of objects for HTML, and a The HTML DOM defines a standard set of objects for HTML, and a standard way to access and manipulate them.standard way to access and manipulate them.

The DOM defines a standard for accessing documents like HTML The DOM defines a standard for accessing documents like HTML and XML :and XML :– "The W3C Document Object Model (DOM) is a platform and "The W3C Document Object Model (DOM) is a platform and

language-neutral interface that allows programs and scripts to language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style dynamically access and update the content, structure, and style of a document."of a document."

The DOM is separated into 3 different parts / levels:The DOM is separated into 3 different parts / levels:

– Core DOM - standard model for any structured documentCore DOM - standard model for any structured document– XML DOM - standard model for XML documents XML DOM - standard model for XML documents – HTML DOM - standard model for HTML documents. HTML DOM - standard model for HTML documents.

The DOM defines the The DOM defines the objects and propertiesobjects and properties of all document of all document elements, and the elements, and the methodsmethods (interface) to access them. (interface) to access them.

Page 4: Javascript DHTML

CSSCSS

CSS is the W3C standard style and layout model for HTML.CSS is the W3C standard style and layout model for HTML. CSS allows web developers to control the style and layout of web CSS allows web developers to control the style and layout of web

pages.pages. HTML 4 allows dynamic changes to CSS.HTML 4 allows dynamic changes to CSS. DHTML is about using JavaScript and DOM to change the style and DHTML is about using JavaScript and DOM to change the style and

positioning of HTML elements.positioning of HTML elements.

Page 5: Javascript DHTML

What is JavaScript?What is JavaScript?

JavaScript is a scripting language that enables web JavaScript is a scripting language that enables web developers/designers to build more functional and interactive developers/designers to build more functional and interactive websites.websites.

Common uses of JavaScript include:Common uses of JavaScript include: Alert messages Alert messages Popup windows Popup windows Dynamic dropdown menus Dynamic dropdown menus Form validation Form validation Displaying date/time Displaying date/time

JavaScript usually runs on the JavaScript usually runs on the client-sideclient-side (the browser's side). (the browser's side). Java script is embedded in web page and interpreted by browser. Java script is embedded in web page and interpreted by browser.

Page 6: Javascript DHTML

Client vs Server side ProcessingClient vs Server side Processing

Advantages of processing on Advantages of processing on client client : :

user interactions can be managed on the client user interactions can be managed on the client reduces load on server (e.g. doing transformations reduces load on server (e.g. doing transformations on client, fewer round trips to server) on client, fewer round trips to server)

Advantages of processing on Advantages of processing on server server : :

don't have to worry about making code cross-don't have to worry about making code cross- browser compatible browser compatible don't have to expose all data to clients don't have to expose all data to clients

Page 7: Javascript DHTML

What do I need to create Javascript?What do I need to create Javascript?

You can create JavaScript using the same equipment You can create JavaScript using the same equipment you use when creating HTML. That is: you use when creating HTML. That is: – Text editorText editor.. For example, Notepad (for Windows), For example, Notepad (for Windows),

Pico (for Linux), or Simpletext (Mac). Pico (for Linux), or Simpletext (Mac). – Web BrowserWeb Browser. For example, Internet Explorer or . For example, Internet Explorer or

Firefox. You will need to ensure JavaScript is enabled Firefox. You will need to ensure JavaScript is enabled within your browser's settings (this is normally within your browser's settings (this is normally enabled by default). enabled by default).

Page 8: Javascript DHTML

How do I check if my browser has JavaScript How do I check if my browser has JavaScript enabled?enabled?

You normally do this by checking your browser's You normally do this by checking your browser's optionsoptions. This will . This will depend on the browser you're using. Instructions for some of the depend on the browser you're using. Instructions for some of the more common browsers are below:more common browsers are below:

Internet Explorer (6.0):Internet Explorer (6.0): Go to Go to ToolsTools from the top menu from the top menu Select Select Internet OptionsInternet Options Click on the Click on the SecuritySecurity tab tab Click Click Custom LevelCustom Level Scroll down until you see the Scroll down until you see the ScriptingScripting section section Ensure that the Ensure that the Active ScriptingActive Scripting option is set at option is set at EnabledEnabled Click Click OKOK

Page 9: Javascript DHTML

How do I check if my browser has JavaScript How do I check if my browser has JavaScript enabled?enabled?

Mozilla Firefox (1.5):Mozilla Firefox (1.5):Go to Go to ToolsTools from the top menu from the top menu Select Select OptionsOptions Click on the Click on the ContentContent button button Ensure that the Ensure that the Enable JavaScriptEnable JavaScript option is option is

checked checked Click Click OKOK

Page 10: Javascript DHTML

Using Java scriptUsing Java script

Embedded :Embedded : Java script can be written in same .html file using Java script can be written in same .html file using

script tag.script tag.Example:Example: Js1.html Js1.html

External :External :Linking to an external JavaScript file.Linking to an external JavaScript file. Java script is in a file .js get call in a file .html inside Java script is in a file .js get call in a file .html inside

script tag.script tag.Example :Example :

ex.htmlex.htmlxxx.jsxxx.js

Page 11: Javascript DHTML

Using HTML element in JavascriptUsing HTML element in Javascript

You can use HTML Elements in the Scripting code.You can use HTML Elements in the Scripting code. Example :Example :

Js2.htmlJs2.html

Page 12: Javascript DHTML

Javascript Pop boxesJavascript Pop boxes Types of Popups :Types of Popups : JavaScript has three different types of popup box JavaScript has three different types of popup box

available. They are:available. They are:AlertAlert

Displays a message to the user. Displays a message to the user. ConfirmConfirm

Asks the user to confirm something. Often, this is Asks the user to confirm something. Often, this is in conjunction with another (potentially significant) in conjunction with another (potentially significant) action that the user is attempting to perform. action that the user is attempting to perform.

PromptPrompt

Prompts the user for informationPrompts the user for information

Page 13: Javascript DHTML

ExampleExample

AlertAlert<script type="text/javascript"><script type="text/javascript">function disp_alert() {function disp_alert() {

alert("Hello again! This is how we" + '\n' + "add line breaks to an alert("Hello again! This is how we" + '\n' + "add line breaks to an alert box!");alert box!");

} } </script></script>

Confirm:Confirm:<script type="text/javascript"><script type="text/javascript">function disp_confirm() {function disp_confirm() {var r=confirm("Press a button");var r=confirm("Press a button");if (r==true)if (r==true)

document.write("You pressed OK!");document.write("You pressed OK!");elseelse

document.write("You pressed Cancel!");document.write("You pressed Cancel!");}}</script></script>

Page 14: Javascript DHTML

ExampleExample

Prompt:Prompt:function disp_prompt()function disp_prompt(){{

var name=prompt("Please enter your var name=prompt("Please enter your name",“Priya"); name",“Priya");

if (name!=null && name!="")if (name!=null && name!="") document.write("Hello " + name + "! How document.write("Hello " + name + "! How

are are you today?");you today?");}}

Page 15: Javascript DHTML

Event HandlerEvent Handler

If we place the above JavaScript between the 'head' tags If we place the above JavaScript between the 'head' tags (or 'body' tags), it will run as soon as we load the page.(or 'body' tags), it will run as soon as we load the page.

Now this is fine - as long as you want it to run as soon as Now this is fine - as long as you want it to run as soon as the page loads!the page loads!

But, what if you don't want it to run as soon as the page But, what if you don't want it to run as soon as the page loads? What if you only want it to run when a user clicks loads? What if you only want it to run when a user clicks on a button?on a button?

Easy! This is where you need to use an "event handler".Easy! This is where you need to use an "event handler".

Page 16: Javascript DHTML

What’s an Event Handler?What’s an Event Handler?

In JavaScript/HTML, an In JavaScript/HTML, an event handlerevent handler allows you to attach your allows you to attach your JavaScript to your HTML elements. JavaScript to your HTML elements.

Event handlers allow your web page to detect when a given "event" Event handlers allow your web page to detect when a given "event" has occurred, so that it can run some JavaScript code. An example has occurred, so that it can run some JavaScript code. An example of an "event" could be say, a click on an HTML element.of an "event" could be say, a click on an HTML element.

In your code, an event handler is simply a special attribute that you In your code, an event handler is simply a special attribute that you add to your HTML element. For example, to run some JavaScript add to your HTML element. For example, to run some JavaScript when the user clicks on an element, you add the onClick attribute to when the user clicks on an element, you add the onClick attribute to the element.the element.

The examples below demonstrate this for you.The examples below demonstrate this for you.

pop1.htmlpop1.html

Page 17: Javascript DHTML

Event HandlerEvent Handler

When you use JavaScript like this, you don't need to use When you use JavaScript like this, you don't need to use script tags (like we did above). script tags (like we did above).

Simply place your JavaScript within the event handler Simply place your JavaScript within the event handler and it will work.and it will work.

<input type="button" <input type="button"

onDblClick="alert('Hey, remember to tell your friends onDblClick="alert('Hey, remember to tell your friends about it.com!');“about it.com!');“

value=“Double Click Me!" /> value=“Double Click Me!" />

Page 18: Javascript DHTML

Different Methods of declaring Javascript Different Methods of declaring Javascript VariablesVariables

Declaring one javascript variable Declaring one javascript variable var firstName;var firstName;

Declaring multiple javascript variables Declaring multiple javascript variables var firstName, lastName;var firstName, lastName;

Declaring and assigning one javascript variable Declaring and assigning one javascript variable var firstName = 'Homer'; var firstName = 'Homer';

Declaring and assigning multiple javascript variablesDeclaring and assigning multiple javascript variablesvar firstName = 'Homer', lastName = 'Simpson'; var firstName = 'Homer', lastName = 'Simpson';

Page 19: Javascript DHTML

Rules for declaring Javascript VariablesRules for declaring Javascript Variables

Can contain any letter of the alphabet, digits 0-9, and the Can contain any letter of the alphabet, digits 0-9, and the underscore character. underscore character.

No spaces No spaces No punctuation characters (eg comma, full stop, etc) No punctuation characters (eg comma, full stop, etc) The first character of a variable name cannot be a digit. The first character of a variable name cannot be a digit. JavaScript variables' names are case-sensitive. For JavaScript variables' names are case-sensitive. For

example example firstNamefirstName and and FirstNameFirstName are two different are two different

variables.variables. Example :Example : variable.html variable.html

Page 20: Javascript DHTML

OperatorsOperators

Arithmetic OperatorsArithmetic OperatorsOperatorOperator DescriptionDescription

+ + AdditionAddition-- SubtractionSubtraction* * MultiplicationMultiplication/ / DivisionDivision% % Modulus Modulus ++ ++ IncrementIncrement-- -- DecrementDecrement

Page 21: Javascript DHTML

Assignment OperatorsAssignment Operators

=Assign=Assign +=Add and assign.+=Add and assign.

For example, x+=y is the same as x=x+y.For example, x+=y is the same as x=x+y. -=Subtract and assign.-=Subtract and assign.

For example, x-=y is the same as x=x-y.For example, x-=y is the same as x=x-y. *=Multiply and assign. *=Multiply and assign.

For example, x*=y is the same as x=x*y.For example, x*=y is the same as x=x*y. /=Divide and assign./=Divide and assign.

For example, x/=y is the same as x=x/y.For example, x/=y is the same as x=x/y. %=Modulus and assign. %=Modulus and assign.

For example, x%=y is the same as x=x%y. For example, x%=y is the same as x=x%y.

Page 22: Javascript DHTML

Comparison OperatorsComparison Operators

Operator Operator DescriptionDescription == == Is equal toIs equal to != != Is not equal toIs not equal to > > Greater thanGreater than >=>= Greater than or equal toGreater than or equal to << Less thanLess than <=<= Less than or equal toLess than or equal to

Page 23: Javascript DHTML

Logical / Boolean OperatorsLogical / Boolean Operators

Operator Operator DescriptionDescription && && andand || || oror ! ! NotNot

String OperatorsString Operators : In JavaScript, a : In JavaScript, a stringstring is simply a is simply a piece of text.piece of text.

Operator Operator DescriptionDescription = = AssignmentAssignment + + Concatenate Concatenate += += Concatenate and assignConcatenate and assign

Page 24: Javascript DHTML

String OperatorsString Operators

As a string is a object type it also has some useful As a string is a object type it also has some useful features.features.

length;length;charAt(3);charAt(3); indexOf(‘a’);indexOf(‘a’); lastIndexOf(‘a’);lastIndexOf(‘a’); toLowerCase();toLowerCase(); toUpperCase(myname);toUpperCase(myname); Example :Example : str.html str.html

Page 25: Javascript DHTML

Escape SequenceEscape Sequence

Escape Sequences are :Escape Sequences are : \”\” \’\’ \\\\ \t\t \n\n \r\r

Example: esc.htmlExample: esc.html<script type="text/javascript"><script type="text/javascript"><!-- document.write("They call it an \"escape\" \\ \' <!-- document.write("They call it an \"escape\" \\ \'

character"); -->character"); --></script></script>

Page 26: Javascript DHTML

Conditional StatementsConditional Statements

If Statement:If Statement: When you write code, you will often need to use When you write code, you will often need to use

conditional statementsconditional statements.. A conditional statement refers to a piece of code that A conditional statement refers to a piece of code that

does one thing based on one condition, and another does one thing based on one condition, and another based on another condition.based on another condition.

ExampleExample : if.html : if.html

<script type="text/javascript"><script type="text/javascript">

var myColor = "Blue";var myColor = "Blue";

if (myColor == "Blue") {if (myColor == "Blue") {

document.write("Just like the sky!");document.write("Just like the sky!"); }}

</script></script>

Page 27: Javascript DHTML

Conditional StatementsConditional Statements

If Else:If Else:

<script type="text/javascript"><script type="text/javascript">var myColor = "Red";var myColor = "Red";if (myColor == "Blue") {if (myColor == "Blue") {

document.write("Just like the sky!");document.write("Just like the sky!");}}else {else {

document.write("Didn't pick blue huh?");document.write("Didn't pick blue huh?");}}</script></script>

Page 28: Javascript DHTML

Conditional StatementsConditional Statements

JavaScript If Else If statementJavaScript If Else If statement– The If Else If statement is more powerful than the The If Else If statement is more powerful than the

previous two. previous two. – This is because you can specify many different This is because you can specify many different

outputs based on many different conditions - all within outputs based on many different conditions - all within the one statement. the one statement.

– You can also end with an "else" to specify what to do You can also end with an "else" to specify what to do if none of the conditions are true.if none of the conditions are true.

– Example : ifelseif.htmlExample : ifelseif.html

Page 29: Javascript DHTML

Conditional StatementsConditional Statements

For Loop:For Loop:

<script type="text/javascript"><script type="text/javascript">

for (i = 1; i <= 6; i++)for (i = 1; i <= 6; i++)

{{

document.write("<h" + i + ">This is header " + i);document.write("<h" + i + ">This is header " + i);

document.write("</h" + i + ">");document.write("</h" + i + ">");

}}

</script></script>

Page 30: Javascript DHTML

Conditional StatementsConditional Statements

While loop:While loop:<script type="text/javascript"><script type="text/javascript">

i=0;i=0;while (i<=5)while (i<=5){{

document.write("The number is " + i);document.write("The number is " + i);document.write("<br />");document.write("<br />");i++;i++;

}}</script></script>

Page 31: Javascript DHTML

Conditional StatementsConditional Statements

Do While Loop:Do While Loop:<script type="text/javascript"><script type="text/javascript">

i = 0;i = 0;dodo{{

document.write("The number is " + i);document.write("The number is " + i);document.write("<br />");document.write("<br />");i++;i++;

}while (i <= 5)}while (i <= 5)</script></script>

Page 32: Javascript DHTML

Conditional StatementsConditional Statements

Conditional operator:Conditional operator:Variable = (condition) ? V1: v2 Variable = (condition) ? V1: v2

Random LinkRandom Link<body><body><script type="text/javascript"><script type="text/javascript">

var r=Math.random();var r=Math.random();if (r>0.5)if (r>0.5)document.write("<a href='http://www.w3schools.com'> document.write("<a href='http://www.w3schools.com'> Learn Web Development!</a>");Learn Web Development!</a>");elseelsedocument.write("<a href='http://www.refsnesdata.no'> document.write("<a href='http://www.refsnesdata.no'> Visit Refsnes Data!</a>");Visit Refsnes Data!</a>");

</script></script></body></body>

Page 33: Javascript DHTML

ArraysArrays

Arrays are created using the Array() constructor.Arrays are created using the Array() constructor.

str1.htmlstr1.htmlarray.htmlarray.htmlarray2.htmlarray2.htmlstrsort.htmlstrsort.htmlsort.htmlsort.html Input.htmlInput.html

Page 34: Javascript DHTML

FunctionsFunctions

Writing function :Writing function :

We started by using the We started by using the functionfunction keyword. This tells the keyword. This tells the browser that a function is about to be defined.browser that a function is about to be defined.

After the function name came a curly bracket {. This opens the After the function name came a curly bracket {. This opens the function. There is also a closing bracket later, to close the function. There is also a closing bracket later, to close the function. }function. }

Example :Example :function1.htmlfunction1.htmlfunction.htmlfunction.html

Page 35: Javascript DHTML

Javascript Error HandlingJavascript Error Handling

Try…Catch StatementTry…Catch Statement The JavaScript "Try... Catch" statement helps you The JavaScript "Try... Catch" statement helps you

handle errors in a "nice" way.handle errors in a "nice" way. To use the Try... Catch statement, you take any code To use the Try... Catch statement, you take any code

you think could potentially result in an error, and wrap it you think could potentially result in an error, and wrap it within the "try" statement. You then code what you want within the "try" statement. You then code what you want to happen in the event of an error and wrap that in a to happen in the event of an error and wrap that in a "catch" statement."catch" statement.

Example :Example : try.html try.html The above code will hide the error and present The above code will hide the error and present

something more user friendly to the user. This is something more user friendly to the user. This is because the code with the error was wrapped inside a because the code with the error was wrapped inside a "try" statement. And, because there was an error, the "try" statement. And, because there was an error, the browser outputs whatever is between the "catch" browser outputs whatever is between the "catch" statement.statement.

Page 36: Javascript DHTML

Advance JavaScriptAdvance JavaScript

Page 37: Javascript DHTML

Built in ObjectsBuilt in Objects

Object is collection of named values and associated Object is collection of named values and associated methods.methods.

Good example is Good example is Math objectMath object propertyproperty

Object.propertyNameObject.propertyNamee.g. Math .PIe.g. Math .PI

Method Method

Object.method(parameter)Object.method(parameter)e.g. Math.round(10.1);e.g. Math.round(10.1);

Other objects are :Other objects are :String , Date ,Array String , Date ,Array

Example : ownobj.htmlExample : ownobj.html

Page 38: Javascript DHTML

JAVA SCRIPT MATH OBJECTJAVA SCRIPT MATH OBJECT

Math object methodMath object method• abs() abs() • min()min()• acos() acos() pow()pow()• asin() asin() random()random()• atan() atan() round()round()• ceil() ceil() sin()sin()• cos() cos() sqrt()sqrt()• exp() exp() tan() tan() • floor()floor()• log()log()• max()max()

Page 39: Javascript DHTML

Date objectDate object

getDate()getDate() getMonth()getMonth() getFullYear()getFullYear() getTime()getTime() getHours()getHours() setDate()setDate() setMonth()setMonth() setFullYear()setFullYear() setTime()setTime() setHours()setHours() Example : time.html, date1.html, date2.htmlExample : time.html, date1.html, date2.html


Recommended