1 HTML Documents and JavaScript جاوا اسکریپت و HTML بخش هایی از جاوا اسکریپت نوشته شده توسط Tom Horton & Alfred C. Weaver تکمیل ، ویرایش و ترجمه : گروه.

Slides:



Advertisements
Similar presentations
Introducing JavaScript
Advertisements

JavaScript and the DOM Les Carr COMP3001 Les Carr COMP3001.
JQuery CS 380: Web Programming. What is jQuery? jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling,
1 CSC 551: Web Programming Spring 2004 client-side programming with JavaScript  scripts vs. programs  JavaScript vs. JScript vs. VBScript  common tasks.
1 Programmer-Defined Functions Functions allow program modularization Variables declared in function are local variables Only known inside function in.
The Web Warrior Guide to Web Design Technologies
Page 1 of 26 Javascript/Jscript Ch 7,8,9,10 Vadim Parizher Computer Science Department California State University, Northridge Spring 2003 Slides from.
1 Outline 13.1Introduction 13.2A Simple Program: Printing a Line of Text in a Web Page 13.3Another JavaScript Program: Adding Integers 13.4Memory Concepts.
Information Technology Center Hany Abdelwahab Computer Specialist.
1 JavaScript/Jscript 6 Objects. 2 Introduction Up till now –JavaScript used to illustrate basic programming concepts JavaScript can also –Manipulate every.
Outline IS400: Development of Business Applications on the Internet Fall 2004 Instructor: Dr. Boris Jukic JavaScript: Functions Part I.
1 JavaScript/Jscript 4 Functions. 2 Introduction Programs that solve real-world programs –More complex than programs from previous chapters Best way to.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 11 – JavaScript/Jscript: Functions Outline 11.1Introduction 11.2Program Modules in JavaScript.
CST JavaScript Validating Form Data with JavaScript.
4.1 JavaScript Introduction
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
HTML DOM.  The HTML DOM defines a standard way for accessing and manipulating HTML documents.  The DOM presents an HTML document as a tree- structure.
SEG3210 DHTML Tutorial. DHTML DHTML is a combination of technologies used to create dynamic and interactive Web sites. –HTML - For creating text and image.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
JavaScript Part 1.
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.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 7 - JavaScript: Introduction to Scripting Outline 7.1 Introduction 7.2 Simple Program: Printing.
JavaScript: Objects Outline 12.1 Introduction 12.2 Thinking About Objects 12.3 Math Object 12.4 String Object Fundamentals of Characters and Strings.
Review IDIA 619 Spring 2013 Bridget M. Blodgett. HTML A basic HTML document looks like this: Sample page Sample page This is a simple sample. HTML user.
SEG3210 DHTML Tutorial. DHTML DHTML is a combination of technologies used to create dynamic and interactive Web sites. –HTML - For creating text and image.
Javascript. Outline Introduction Fundamental of JavaScript Javascript events management DOM and Dynamic HTML (DHTML)
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3.
Lesson13. JavaScript JavaScript is an interpreted language, designed to function within a web browser. It can also be used on the server.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
1 JavaScript in Context. Server-Side Programming.
CHAPTER 4 Java Script อ. ยืนยง กันทะเนตร คณะเทคโนโลยีสารสนเทศและการสื่อสาร มหาวิทยาลัยพะเยา 1.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
Intro to JavaScript Scripting language –ECMAScript compliant –Client side vs. server side Syntactic rules –White space –Statement end: ; optional –Comments:
JavaScript, jQuery, and Mashups Incorporating JavaScript, jQuery, and other Mashups into existing pages.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 13 – JavaScript/Jscript: Objects Outline 13.1Introduction 13.2Thinking About Objects 13.3.
 2001 Deitel & Associates, Inc. All rights reserved. 1 Outline 16.1Introduction 16.2Program Modules in JavaScript 16.3Programmer-Defined Functions 16.4Function.
Lecture 10 JavaScript: DOM and Dynamic HTML Boriana Koleva Room: C54
JavaScript - Basic Concepts Prepared and Presented by Hienvinh Nguyen, Afshin Tiraie.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
05 – Java Script (1) Informatics Department Parahyangan Catholic University.
 2000 Deitel & Associates, Inc. All rights reserved. Outline 8.1Introduction 8.2A Simple Program: Printing a Line of Text in a Web Page 8.3Another JavaScript.
 2001 Deitel & Associates, Inc. All rights reserved. 1 Chapter 18 – JavaScript/Jscript: Objects Outline 18.1Introduction 18.2Thinking About Objects 18.3.
1 Chapter 3 – JavaScript Outline Introduction Flowcharts Control Structures if Selection Structure if/else Selection Structure while Repetition Structure.
Jaana Holvikivi 1 Introduction to Javascript Jaana Holvikivi Metropolia.
JavaScript 1 COE 201- Computer Proficiency. Introduction JavaScript scripting language ▫Originally created by Netscape ▫Facilitates disciplined approach.
Java Script About Java Script Document Object Model Incorporating JavaScript Adding JavaScript to HTML Embedding a Javascript External Scripts Javascript.
Web Programming Java Script & jQuery Web Programming.
Chapter 7 - JavaScript: Introduction to Scripting Outline 7.1 Introduction 7.2 Simple Program: Printing a Line of Text in a Web Page 7.3 Another JavaScript.
JavaScript. JavaScript Introduction JavaScript is the world's most popular programming language. It is the language for HTML and the web, for servers,
This is our seminar JavaScript And DOM This is our seminar JavaScript And DOM.
JavaScript and Ajax (JavaScript Environment) Week 6 Web site:
CSE 154 LECTURE 9: THE DOM TREE. The DOM tree The elements of a page are nested into a tree-like structure of objects the DOM has properties and methods.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 12 - JavaScript: Objects Outline 12.1 Introduction 12.2 Thinking About Objects 12.3 Math Object.
INTERNET APPLICATIONS CPIT405 JavaScript Instructor: Rasha AlOmari
WEB SYSTEMS & TECHNOLOGY. Java Script  JavaScript created by Netscape  It is also client side programming  It can be use for client side checks.
 2001 Prentice Hall, Inc. All rights reserved. Outline 1 JavaScript.
JavaScript Mimi Opkins CECS 470. What We’ll Cover Today u What is JavaScript? u What can it do? u How to program your pages using JavaScript u What do.
14 A Brief Look at JavaScript and jQuery.
JavaScript: Objects.
Chapter 12 - JavaScript: Objects
WEB PROGRAMMING JavaScript.
Chapter 12 - JavaScript: Objects
HTML Documents and JavaScript
HTML Documents and JavaScript
Chapter 12 - JavaScript: Objects
Web Programming and Design
Web Programming and Design
Chapter 10 - JavaScript: Functions
Presentation transcript:

1 HTML Documents and JavaScript جاوا اسکریپت و HTML بخش هایی از جاوا اسکریپت نوشته شده توسط Tom Horton & Alfred C. Weaver تکمیل ، ویرایش و ترجمه : گروه 2 ( طایفی ، نوری ، پژاوند ، طیبی، اسدزاده )

2 پیش زمینه ای درباره HTML Many “markup” languages in the past SGML: Standard Generalized Markup Language HTML (Hypertext Markup Language) based on SGML XML (eXtensible Markup Language) “replaces” SGML XHTML is replacing HTML

3 تگ ها و اجزای آنها Example of an element: content Begin and end tags set off a section of a document Has a semantic property by tag-name Modified by attributes “content” can contain other elements Empty-elements: no end tag Note space before />

4 مقدمات ساختاری html Comments: Example: … …. <--- title, meta-tags, etc. (not displayed) <--- main content (displayed)

5 یک مثال کامل An Example An Example Hello World! I am 21. Green Yellow John Mike

6 خروجی مثال

7 مقدمات Text display:,, Structure:,,,, Attributes: Align, text, bgcolor, etc.

8 مقدمات تگ ها Links: … Images: an empty tag Tables Use an editor! Forms: later

9 زبان برنامه نویسی شی گرا An model for describing HTML documents (and XML documents) A standard (ok, standards) Independent of browser, language (ok, mostly) APIs in JavaScript, for Java, etc.

10 DOM You get anything you want from… More info: Object_Model

11 استاندارهای W3C XML, XHTML CSS, XSL XSLT DOM ECMAScript etc

12 جاواسکریپت An example of a “scripting” langauge that is embedded in HTML documents The browser’s display engine must distinguish from HTML and Script statements Others like this: PHP (later in the course)

13 تاریخچه JavaScript created by Netscape JScript created by Microsoft IE and Netscape renderings are slightly different Standardized by European Computer Manufacturers Association (ECMA) org/publications /standards/Ecma-262.htm

14 قالب عمومی Name of web page...script goes here </head...page body here: text, forms, tables...more JavaScript if needed...onload, onclick, etc. commands here

15 ساختار زبانی Case sensitive Object oriented Produces an HTML document Dynamically typed Standard operator precedence Overloaded operators Reserved words

16 ساختار زبانی Division with / is not integer division Modulus (%) is not an integer operator 5 / 2 yields / 2.1 yields % 2 yields % 2.1 yields

17 ساختار زبانی " and ' can be used in pairs Scope rules for variables Strings are very common data types Rich set of methods available Arrays have dynamic length Array elements have dynamic type Arrays are passed by reference Array elements are passed by value

18 دستورات مهم در جاوا اسکریپت code placement document.writeln document tags window.alert user input/output parseInt and parseFloat arithmetic arithmetic comparisons for loops while loops do-while loops if-else variable values in tags math library switch break labeled break continue Booleans

19 دستورات مهم در جاوا اسکریپت functions random numbers rolling dice form input form output submit buttons games arrays searching strings substrings string conversions markup methods

20 فراخوانی جاوا اسکریپت Create functions (non-OO style) Define in header Or load a.js file in header: Functions called in Often in response to events, e.g. Global variables

21 document.writeln Welcome to JavaScript document.writeln( " Welcome to ", "JavaScript Programming! " );

22 document.write Using document.write document.write ( " Welcome to "); document.writeln( "JavaScript Programming! " );

23 window.alert Using window.alert window.alert( "Welcome to\nJavaScript\nProgramming!" ); Click Refresh (or Reload) to run this script again.

24 input/output var firstNumber, // first string entered by user secondNumber, // second string entered by user number1, // first number to add number2, // second number to add sum; // sum of number1 and number2 // read in first number from user as a string firstNumber = window.prompt("Enter first integer", "0" ); // read in second number from user as a string secondNumber = window.prompt( "Enter second integer", "0" ); // convert numbers from strings to integers firstNumber = parseInt(firstNumber); number2 = parseInt( secondNumber ); // add the numbers sum = firstNumber + number2; // display the results document.writeln( " The sum is " + sum + " " );

25 Functions var input1 = window.prompt( "Enter first number", "0" ); var input2 = window.prompt( "Enter second number", "0" ); var input3 = window.prompt( "Enter third number", "0" ); var value1 = parseFloat( input1 ); var value2 = parseFloat( input2 ); var value3 = parseFloat( input3 ); var maxValue = maximum( value1, value2, value3 ); document.writeln( "First number: " + value1 + " Second number: " + value2 + " Third number: " + value3 + " Maximum is: " + maxValue ); // maximum method definition (called from above) function maximum( x, y, z ) { return Math.max( x, Math.max( y, z ) ); }

26 Random Numbers var value; document.writeln( " Random Numbers " + " " ); for ( var i = 1; i <= 20; i++ ) { value = Math.floor( 1 + Math.random() * 6 ); document.writeln( " " + value + " " ); if ( i % 5 == 0 && i != 20 ) document.writeln( " " ); } document.writeln( " " );

27 Roll the Die var frequency1 = 0, frequency2 = 0, frequency3 = 0, frequency4 = 0, frequency5 = 0, frequency6 = 0, face; // summarize results for ( var roll = 1; roll <= 6000; ++roll ) { face = Math.floor( 1 + Math.random() * 6 ); switch ( face ) { case 1: ++frequency1; break; case 2: ++frequency2; break; case 3: ++frequency3; break; case 4: ++frequency4; break; case 5: ++frequency5; break; case 6: ++frequency6; break; } document.writeln( " " );.....

28 Rules of Craps First roll: 7 or 11 is a win 2, 3, or 12 is a lose otherwise, roll becomes your point Subsequent rolls: rolling your point is a win 7 or 11 is a lose otherwise continue to roll

29 Craps // variables used to test the state of the game var WON = 0, LOST = 1, CONTINUE_ROLLING = 2; // other variables used in program var firstRoll = true, // true if first roll sumOfDice = 0, // sum of the dice myPoint = 0, // point if no win/loss on first roll gameStatus = CONTINUE_ROLLING; // game not over yet

30 Craps // process one roll of the dice function play() { if ( firstRoll ) { // first roll of the dice sumOfDice = rollDice(); switch ( sumOfDice ) { case 7: case 11: // win on first roll gameStatus = WON; document.craps.point.value = ""; // clear point field break; case 2: case 3: case 12: // lose on first roll gameStatus = LOST; document.craps.point.value = ""; // clear point field break;

31 Craps default: // remember point gameStatus = CONTINUE_ROLLING; myPoint = sumOfDice; document.craps.point.value = myPoint; firstRoll = false; } else { sumOfDice = rollDice(); if ( sumOfDice == myPoint ) gameStatus = WON; else if ( sumOfDice == 7 ) gameStatus = LOST; }

32 Craps if ( gameStatus == CONTINUE_ROLLING ) window.alert ("Roll again"); else { if ( gameStatus == WON ) { window.alert ("Player wins. " + "Click Roll Dice to play again."); document.craps.point.value = " "; } else { window.alert ("Player loses. " + "Click Roll Dice to play again."); document.craps.point.value = " "; } firstRoll = true; }

33 Craps // roll the dice function rollDice() { var die1, die2, workSum; die1 = Math.floor( 1 + Math.random() * 6 ); die2 = Math.floor( 1 + Math.random() * 6 ); workSum = die1 + die2; document.craps.firstDie.value = die1; document.craps.secondDie.value = die2; document.craps.sum.value = workSum; return workSum; }

34 Poker Hand function rand1toN(N) { return Math.floor( 1+Math.random()*N ); } function dealcard(card) { var rank = new Array(0,"A","2","3","4","5","6","7", "8","9","T","J","Q","K"); var suit = new Array(0, "Spades", "Hearts", "Diamonds", "Clubs"); card[0] = rank[rand1toN(13)]; card[1] = suit[rand1toN(4)]; }

35 Poker Hand var card = new Array(2); var player = new Array(10); var dealer = new Array(10); for (var i=0; i<=4; i++) { dealcard(card); player[i*2] = card[0]; player[i*2+1] = card[1]; dealcard(card); dealer[i*2] = card[0]; dealer[i*2+1] = card[1]; }

36 Poker Hand document.writeln(" PLAYER "); document.writeln(" "); for (var i=0; i<=4; i++) { document.writeln(" " + player[i*2] + " " + " " + player[i*2+1] + " "); } document.writeln(" ");

37 Character Processing var s = "ZEBRA"; var s2 = "AbCdEfG"; document.writeln( " Character at index 0 in '"+ s + '" is " + s.charAt( 0 ) ); document.writeln( " Character code at index 0 in '" + s + "' is " + s.charCodeAt( 0 ) + " " ); document.writeln( " '" + String.fromCharCode( 87, 79, 82, 68 ) + "' contains character codes 87, 79, 82 and 68 " ); document.writeln( " '" + s2 + "' in lowercase is '" + s2.toLowerCase() + "'" ); document.writeln( " '" + s2 + "' in uppercase is '" + s2.toUpperCase() + "' " );

38 Dates and Times var current = new Date(); document.writeln(current); document.writeln( " String representations and valueOf " ); document.writeln( "toString: " + current.toString() + " toLocaleString: " + current.toLocaleString() + " toUTCString: " + current.toUTCString() + " valueOf: " + current.valueOf() ); document.writeln( " Get methods for local time zone " ); document.writeln( "getDate: " + current.getDate() + " getDay: " + current.getDay() + " getMonth: " + current.getMonth() + " getFullYear: " + current.getFullYear() + " getTime: " + current.getTime() + " getHours: " + current.getHours() + " getMinutes: " + current.getMinutes() + " getSeconds: " + current.getSeconds() + " getMilliseconds: " + current.getMilliseconds() + " getTimezoneOffset: " + current.getTimezoneOffset() );

39 Dates and Times document.writeln( " Specifying arguments for a new Date " ); var anotherDate = new Date( 1999, 2, 18, 1, 5, 3, 9 ); document.writeln( "Date: " + anotherDate ); document.writeln( " Set methods for local time zone " ); anotherDate.setDate( 31 ); anotherDate.setMonth( 11 ); anotherDate.setFullYear( 1999 ); anotherDate.setHours( 23 ); anotherDate.setMinutes( 59 ); anotherDate.setSeconds( 59 ); document.writeln( "Modified date: " + anotherDate );

40 Events JavaScript can execute a statement (typically, call a function) when an event occurs

41 Events onsubmit - call when submit button is clicked onclick - call when this button is clicked onreset - call when the reset button is clicked onload - call after page loads onmouseover - call when mouse pointer enters image area onmouseout - call when mouse pointer leaves image area onfocus - call when control receives focus onblur - call when a control loses focus onchange - call when a control loses focus and the value of its contents has changed many more

HTML Control JavaScript can change attr of Dom getElementById getElementsByClassName getElementsByName document.getElementById(‘pId’).innerHTML=“ My Name Is Masoud Tayefi”; document.getElementById(‘inputId’).value; 42

HTML Control 43 namedescription getElementByIdreturns array of descendents with the given tag, such as "div" getElementsByTagNamereturns array of descendents with the given tag, such as "div" getElementsByNamereturns array of descendents with the given name attribute (mostly useful for accessing form controls) querySelectorquerySelector *returns the first element that would be matched by the given CSS selector string querySelectorAllquerySelectorAll *returns an array of all elements that would be matched by the given CSS selector string

jQuery jQuery is a cross-platform JavaScript library designed to simplify the client- side scripting of HTML 44

jQuery Include 45

We cannot use the DOM before the page has been constructed. jQuery gives us a more compatibile way to do this. The DOM way The direct jQuery translation The jQuery way window.onload = function() { // do stuff with the DOM } $(document).ready(function() { // do stuff with the DOM }); $(function() { // do stuff with the DOM });

Dom Tree 47

jQuery Control 48 // id selector var elem = $("#myid"); // group selector var elems = $("#myid, p"); // context selector var elems = $("#myid < div p"); // complex selector var elems = $("#myid < h1.special:not(.classy)");

jQuery Selector 49 DOM methodjQuery equivalent getElementById("id")$("#id") getElementsByTagName("tag")$("tag") getElementsByName("somename")$("[name='somename']") querySelector("selector")$("selector") querySelectorAll("selector")$("selector")

The jQuery object 50 The $ function always (even for ID selectors) returns an array-like object called a jQuery object. The jQuery object wraps the originally selected DOM objects. You can access the actual DOM object by accessing the elements of the jQuery object. // false document.getElementById("id") == $("#myid"); document.querySelectorAll("p") == $("p"); // true document.getElementById("id") == $("#myid")[0]; document.getElementById("id") == $("#myid").get(0); document.querySelectorAll("p")[0] == $("p")[0];

51 You can use querySelectorAll() and querySelector() on any DOM object. When you do this, it simply searches from that part of the DOM tree downward. Programmatic equivalent of a CSS context selector var list = document.getElementsByTagName("ul")[0]; var specials = list.querySelectorAll('li.special'); DOM context identification

findfind / context parameter 52 jQuery gives two identical ways to do contextual element identification var elem = $("#myid"); // These are identical var specials = $("li.special", elem); var specials = elem.find("li.special");

Types of DOM nodes 53 This is a paragraph of text with a link in it.

Traversing the DOM tree 54

Scripting var x,y; if (self.innerHeight) { // all except Explorer x = self.innerWidth; y = self.innerHeight; } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode x = document.documentElement.clientWidth; y = document.documentElement.clientHeight; } else if (document.body) { // other Explorers x = document.body.clientWidth; y = document.body.clientHeight; } 55 var x = $(window).width(); var y = $(window).height();

jQuery CSS Selectors element {} #id {}.class {} selector1, selector2 {} ancestor descendant {} parent > child {} :nth-child() {} 56 $('element') $('#id') $('.class') $('selector1, selector2') $('ancestor descendant') $('parent > child') $(':nth-child(n)')

CSS Attribute Selectors 57 $('input[name=firstname\\[\\]]') $('[title]') has the attribute $('[attr="val"]')attr equals val $('[attr!="val"]')attr does not equal val $('[attr~="val"]')attr has val as one of space- sep. vals $('[attr^="val"]')attr begins with val $('[attr$="val"]')attr ends with val $('[attr*="val"]')attr has val anywhere within

Custom Form Selectors $('div.myclass :checkbox') $(':input'),,, $(':text') $(':radio') $(':button'), $(':selected') etc. 58

Chaining 59 $('a').parent('li').siblings().find('a') $('a').removeClass('old').addClass('new'); $('a').addClass('foo').parent('li').removeClass('foo') var lis = $('.container li:first').addClass('first-li').next().addClass('second-li').end().nextAll().addClass('not-first-li').end(); // unnecessary; added for symmetry

Looping 60 $('li').removeClass('myclass'); //implicit $('li').each(function(index) { //explicit $(this).append( ' #' + (index+1) ); });

jQuery Samples $('#textbox').hide(); var h1 = document.CreateElement("h1"); h1.innerHTML = "my text"; document.getElementsByTagName('body')[0].appendChild(h1); $('body').append( $(" ").html("my text") ; $(document).ready(function(){ //Script goes here }); $("h1.mainTitle") $("h1.mainTitle#firstHeading") 61

jQuery Samples 62

jQuery Samples 63

jQuery Event 64

jQuery Event 65

با تشکر از حوصله و تحمل شما والسلام 66