Course Syllabus COURSE NAME

Size: px
Start display at page:

Download "Course Syllabus COURSE NAME"

Transcription

1 Course Syllabus COURSE NAME Internet Technology COURSE CODE COMP230 CREDIT 3 CONTACT HOURS 4 (2 + 2) PREREQUISITE COMP151 : Introduction to Algorithms and Programming LEARNING OUTCOMES SYNOPSIS CONTENTS Understand the major protocols for internetworking in today s Internet Understand client-server architecture Perform basic website design using XHTML and CSS Perform client side programming using JavaScript Gain the ability to learn new Internet technologies by yourself Learn how to work individually and in groups Initially, students will focus on the general structure of the Internet and the different components that constitute its building blocks. Next, students will extensively study XHTML and Cascading Style Sheets (CSS), which provide the underlying structure of today's web sites. Once these are mastered, students will explore a client-side scripting language which enables web site developers to greatly enhance the end user's experience. The course will cover, in depth: The Architecture of the Internet and the Web. XHTML. CSS. The Document Object Module (DOM). DHTML with JavaScript. Client Side Programming with JavaScript. LECTURES 1. Introduction (4 hours) The course will start by defining the Internet and detail its building blocks. Next, it will explore the different services provided by the internet giving some examples on the use of each one of the services. It then goes into describing the TCP/IP protocol with distinguishes the internet from the rest of the networks. 2. XHTML (Extendible Markup Language) (6 hours) All the elements of the extendible markup language XHTML will be studied in detail. All along the difference between HTML and XHTML is highlighted. Students will be asked to develop a web site using most of the learned xhtml elements. 3. CSS (Cascading Style Sheet) (6 hours) The use of CSS (cascading style sheets) in formatting and laying out the

2 information on a web page will be explained. The lectures will cover most of CSS rules. The emphasis will be on CSS backgrounds, background colors, CSS positioning, CSS text, CSS fonts, and CSS links. The different selectors will be used when applying a CSS rule to the page elements. 4. JavaScript (6 hours) These lectures will cover JavaScript in detail including: variables, arrays, decisions, loops and switch statement, functions, built in functions, string management, and comments. 5. DHTML (4 hours) Dynamic HTML, or DHTML, is a collection of technologies used together to create interactive and animated web sites using a combination of a static markup language (such as XHTML), a client-side scripting language (such as JavaScript), a presentation definition language (such as CSS), and the Document Object Model (DOM). DHTML allows scripting languages to change variables in a web page's definition language, which in turn affects the look and function of otherwise "static" XHTML page content, after the page has been fully loaded and during the viewing process. In these lectures, students will understand the DOM and will know how to use it to select the appropriate element in the web page that needs a special effect. 6. Validation (4 hours) In these lectures, students will learn how to use XHTML forms and JavaScript to validate user input and send the appropriate message to the user. 7. Revision (2 hours) General revision Total ( 32 hours) ASSESSMENTS Course Work Tests 30%, Quizzes 10%, Assignments 10%, Project 10% Final 40% Examination REFERENCES Internet Technology and E-Commerce Author: Alison Gausey, Publisher Plgave Macmillar ISBN Internet & World Wide Web How to Program? Author P.J Deitel, H.M Deitel. Publisher Pearson Education. 2. Computer Networking A Top-Down Approach Featuring the Internet. 3rd Ed. Author James F. Kurose, Keith W. Ross. Publisher Wesley Longman, Inc Text Book Additional references

3 1 1 Introduction to Computers and the Internet

4 History of the Internet and World Wide Web 2 ARPANET Implemented in late 1960 s by ARPA (Advanced Research Projects Agency of DOD) Networked computer systems of a dozen universities and institutions with 56KB communications lines Grandparent of today s Internet Became clear that key benefit was allowing fast communication between researchers electronic-mail ( )

5 History of the Internet and World 3 Wide Web Huge variety of networking hardware and software appeared ARPA achieved inter-communication between all platforms with development of the IP Combined set of protocols called TCP/IP The Internet Limited to universities and research institutions Military became big user Next, government decided to access Internet for commercial purposes

6 History of the Internet and World 4 Wide Web Internet traffic grew Businesses spent heavily to improve Internet Strong competition among communications carriers and hardware and software suppliers Resulted in massive bandwidth increase and plummeting costs. Tim Berners-Lee invents HyperText Markup Language (HTML) - Also writes communication protocols to form the backbone new information system = World Wide Web - Hypertext Transfer Protocol (HTTP) a communications protocol used to send information over the web Web use exploded with availability in 1993 of the Mosaic browser Marc Andreessen founds Netscape

7 5 World Wide Web Consortium (W3C) W3C Founded in 1994 by Tim Berners-Lee Homepage at Goals Internet universally accessible Standardization - Extensible HyperText Markup Language (XHTML), Cascading Style Sheets (CSS), HyperText Markup Language (HTML now considered a legacy technology) and the Extensible Markup Language (XML).

8 6 Web noticeable shift in how people and businesses were using the web and developing web-based applications The term Web 2.0 was coined by Dale Dougherty of O Reilly Web 2.0 definition = companies use the web as a platform to create collaborative, community-based sites (e.g., social networking sites, blogs, wikis, etc.). Web 1.0 (1990s and early 2000s) focused on a small number of companies and advertisers producing content for users to access Web 2.0 involves the Web 1.0 is as a lecture, Web 2.0 is a conversation Websites like MySpace, Facebook, Flickr, YouTube, ebay and Wikipedia, users create the content, companies provide the platforms.

9 JavaScript: Object-Based Scripting for the Web 7 JavaScript Attractive package for advancing level of programming language education Object-based language Free as part of today s most popular Web browsers Powerful scripting language - Portable - Programs execute interpretively on client machines

10 8 C, C++ and Java C developed by Dennis Ritchie at Bell Laboratories development language of the UNIX operating system virtually all new major operating systems are written in C and/or C++ C++ developed by Bjarne Stroustrup in early 1980s provides capabilities for object-oriented programming Java developed by Sun Microsystems in 1991 and announced formally in May 1995 Java is now used to - develop large-scale enterprise applications - enhance the functionality of web servers - provide applications for consumer devices

11 9 BASIC, Visual Basic, Visual C++, C# and.net BASIC Developed in the mid-1960s at Dartmouth College Primary purpose was to familiarize novices with programming techniques Microsoft s Visual Basic language Based on Basic One of the most popular programming languages in the world Microsoft s.net platform Provides the capabilities developers need to create computer applications that can execute on computers distributed across the Internet - Visual Basic (based on the original BASIC) - Visual C++ (based on C++) - Visual C# (based on C++ and Java)

12 10 Software Technologies (Cont.) Linux Open source operating system Apache Most popular open source web server MySQL Open source database management system PHP Most popular open source server-side scripting language for developing Internet-based applications LAMP Linux, Apache, MySQL and PHP (or Perl or Python) Game programming Software techniques used in game programming Adobe Flash CS3

13 1 2 Web Browser Basics: Internet Explorer and Firefox

14 2 Introduction to Web Browsers Internet is an essential medium for worldwide communication Web browsers Software programs that access web s rich content www portion of the Internet. hyperlinked documents written in XHTML and rich media Popular web browsers Microsoft s Internet Explorer Mozilla s Firefox Apple s Safari Opera Software s Opera Google s Chrome

15 3 Connecting to the Internet Computer + web browser software + ISP = Internet access Computer must have modem or network card - Modem - hardware that converts data to audio tones and transmits the data over phone lines - Network card or network interface card (NIC) - hardware that allows a computer to connect to the Internet through a network or a high-speed Internet connection, Internet Service Provider (ISP) - connects computers to the Internet Must consider bandwidth and cost for ISP Broadband DSL Dial-up service Fiber optics

16 Internet Explorer 7 and Firefox 2 Features 4 URL (Uniform Resource Locator) Each web page on the Internet has unique URL Usually begin with http-:// or ((s stands for secured, it means that the data will be encrypted before it is submitted)) Hyperlinks Visual elements on web pages that when clicked, load a specified web document Can reference other web pages, addresses, files and more Download files Tabbed Browsing Allows the user to browse multiple pages without many windows Using the History Feature List of previously visited URLs in chronological order

17 Customizing Browser Settings 5 Browser settings Determine how sites are displayed How security measures are applied How outputs are rendered Privacy settings. Controls what the browsers remember about your online activities like the search, forms data, history, downloads etc Security options How much information you want to hide from unfamiliar sites How much of the site s content will be blocked Personal home page Web page that loads when the browser is first opened History options Web page cache Previously viewed sites

18 6 Searching the Internet Internet is wealth of information Search engines help locate more specific information on a given topic - Google ( - Yahoo! ( - Bing ( Use databases that facilitate quick information retrieval Metasearch engines (do not maintain databases) - Send the search criteria to other search engines

19 7 Keeping Track of Your Favorite Sites Organize and track Web browsing history (URL and title) Bookmarking Favorites menu s: Favorites can be categorized and grouped into folders Most browsers have their own version of Favorites or Bookmarks.

20 File Transfer Protocol (FTP) 8 File Transfer Protocol (FTP) Set of rules by which computers transfer data over the Internet URL begins with ftp:// rather than -http Accessed either with the web browser or software that supports FTP FTP site can be browsed as though they were files on the local computer Files can be downloaded FTP site may require login FTP can also be used on the Internet for Uploading files Downloading files File-managing tasks

21 1 3 Dive Into Web 2.0

22 2 Introduction In 2003, noticeable shift in how people and businesses were using the web and developing web-based applications Web = companies use the web as a platform to create collaborative, community-based sites (e.g., social networking sites, blogs, wikis, etc.) Growth of Web 2.0 key factors Hardware keeps getting cheaper and faster, with memory capacities and speeds increasing at a rapid rate Broadband Internet use has exploded Availability of abundant open source software has resulted in cheaper (and often free) customizable software options

23 3 What Is Web 2.0? Web 1.0 focused on a relatively small number of companies and advertisers producing content = brochure web Web 2.0 involves the user. Web 1.0 is as a lecture and Web 2.0 is a conversation. Many Web 2.0 companies are built almost entirely on user-generated content and harnessing collective intelligence. Google, MySpace, Flickr, YouTube and Wikipedia, users create the content, while the sites provide the platforms. The user is not only contributing content and developing open source software, but directing how media is delivered, and deciding which news and information outlets you trust. Social bookmarking sites such as del.icious Social media sites such as Digg or Reddit Social networking, MySpace, Facebook, LinkedIn, and Second Life

24 4 What Is Web 2.0? (Cont.) Web development technologies = Ajax, XHTML, Cascading Style Sheets, JavaScript, the Document Object Model (DOM), and XML. Rich Internet Applications (RIAs) web applications that offer the responsiveness and rich GUI features of desktop applications Key tools for building RIAs = Adobe s Flex, Microsoft s Silverlight, ASP.NET Ajax and Sun s JavaServer Faces Other Web development tools and technologies = Adobe s Dreamweaver, JSON, the web servers IIS and Apache, MySQL, PHP and ASP.NET Web services allow you to incorporate functionality from existing applications into your own applications quickly and easily. Amazon Web Services Google Maps web services ebay web services

25 5 Search Search engines are the primary tools people use to find information on the web Traffic to the major search engines is growing rapidly Americans conducted 8 billion search queries in June 2007, up 26% from the previous year. Search engines have gained popularity by helping users quickly find and filter the information Google Search Google is the leading search and online advertising company founded by Larry Page and Sergey Brin Google s success in search is largely based on its PageRank algorithm and its unique infrastructure of servers Google offers specialty search engines for images, news, videos, blogs and more. Google web services build Google Maps and other Google services into your applications AdWords, Google s pay-per-click (PPC) contextual advertising program AdSense is Google s advertising program for publishers

26 6 Search (Cont.) Yahoo! Yahoo! started in 1994 by Jerry Yang and David Filo as a web directory rather than a search engine Yahoo! also expanded into other areas, becoming a popular provider of , user groups and more Vertical Search Vertical search engines are specialists (focusing on specific topics) in comparison to generalists (e.g., Google and Yahoo Goal of providing you with a smaller number of more relevant results Popular vertical search engines include travel sites (such as Kayak or Expedia), real-estate sites (such as Zillow or Trulia), job search sites (such as Indeed or Monster) and shopping search engines (such as Shopzilla and MySimon) Location-Based Search Location-based search uses geographic information about the searcher to provide more relevant search results

27 7 Search (Cont.) Creating Customized Search Engines Rollyo a build-your-own customized search engine website allows you to explore, create and personalize search engines ( searchrolls ) created by others Search Engine Optimization (SEO) Process of designing and tuning your website to maximize your findability and improve your rankings in organic (non-paid) search engine results - Maximize traffic Search Engine Marketing (SEM) Method of promoting your website to increase traffic and search results by raising the site s visibility on search engine results pages Search Engine Strategies Conferences Search Engine Strategies is a global conference series focused on search engine advertising (including current SEO and SEM issues).

28 8 Content Networks Content networks = websites or collections of websites that provide information in various forms articles, wikis, blogs, etc filters the vast amounts of information on the Internet

29 9 User-Generated Content Key to success for many of today s leading Web 2.0 companies = usergenerated content articles home videos Photos implicitly generated Collective Intelligence Collaboration can result in smart ideas Wikis Allow users to edit existing content and add new information Wikipedia Wikia Media-Wiki open source software SocialText Using wikis for project collaboration reduces s and phone calls between employees, while allowing the ability to closely track a project s changes

30 10 User-Generated Content (Cont.) Collaborative Filtering Users might submit false or faulty information - Wikipedia people deliberately adding false information to entries - Web 2.0 companies rely on the community to help police their sites Wisdom of Crowds Large diverse groups of people can be smarter than a small group of specialists

31 11 Blogging History of Blogging Blogs are websites consisting of entries listed in reverse chronological order Grown exponentially in recent years because of easy-to-use blogging software and increasingly economical Internet access Blogs can also now incorporate media, such as music or videos Blogging and Journalism Encouraged citizen journalism Significant news resource Many bloggers are recognized as members of the media

32 12 Social Networking Social networking sites Allow users to keep track of their existing interpersonal relationships and form new ones Network Effects Increased value of a network as its number of users grows Network effects make it difficult to break into markets already claimed by successful companies Friendster Early leader in social networking MySpace Pages are personal and customizable News Corp, which acquired MySpace in 2005 for $580 million

33 13 Social Networking (Cont.) Facebook Facebook has over 200 million users LinkedIn Business-oriented social networking site - stay in touch with professional contacts - network with new contacts - check references - find a job or a potential employee - privacy concerns are more

34 14 Social Networking (Cont.) Second Life Second Life, developed by Linden Labs, is a 3D virtual world with millions of inhabitants Users create avatars, digital representations of themselves that they can use to meet other users with similar interests, conduct business, participate in group activities, take classes and more Users can create objects and add scripts (to animate the objects) in the virtual world

35 15 Social Media Social media = any media shared online (e.g., videos, music, photos, news, etc YouTube Launched in late 2005 and is the leading Internet video site Entire site is based on user-generated content Can browse videos by category, tag, or by following related video links Users can subscribe to other users content, share videos with friends by , or embed videos directly into their blogs or other websites YouTube was acquired by Google for $1.65 billion.

36 16 Social Media Internet TV Many mass-media companies now offer full-length episodes of popular television shows Limited by copyright issues Internet TV allows advertisers to target their markets more precisely than with broadcast television Digg Features news, videos and podcasts, all posted and rated by users Gained popularity by allowing users to digg or bury posts and user comments Digg uses collaborative filtering Last.fm Last.fm is an Internet radio website that uses Web 2.0 concepts to make music recommendations and build communities

37 17 Social Media (Cont.) Digital Rights Management (DRM) Add software to media files to prevent them from being misused Protect digital products from illegal distribution Podcasting Popularized by Apple s ipod portable media player. Podcast is a digital audio file (e.g., an.mp3) that often takes on the characteristics of a radio talk show Introduced a more democratic form of radio broadcasting

38 18 Social Bookmarking Social bookmarking sites = share your Internet bookmarks (e.g., your favorite websites, blogs, and articles) through a website. del.icio.us Ma.gnolia

39 19 Software Development Key to Web 2.0 software development KIS (keep it simple; keep it small The Webtop Web has now become an application, development, delivery, and execution platform Webtop, or web desktop, allows you to run web applications in a desktoplike environment in a web browser Operating-system independent applications Software as a Service (SaaS) Application software that runs on a web server rather than being installed on the client computer - Examples: Most Google software and Microsoft s Windows Live and Office Live. Collaborating on projects with co-workers across the world is easier Information stored on a web server instead of on a single desktop

40 20 Software Development Perpetual Beta and Agile Development Shift away from the traditional software release cycle (i.e., new software releases take months or years) Now a greater focus on agile software development, which refers to development of fewer features at a time with more frequent releases Open Source - Made possible by using the web as a platform - The Internet is a dynamic medium Not always free, but the source code is available (under license) to developers, who can customize it to meet their unique needs - Linux operating systems Red Hat or Ubuntu Because the source code is available to everyone, users can look to the community for bug fixes and plug-ins Over 150,000 open source projects are under development - Examples: Firefox web browser, the Apache web server, the MySQL database system, DotNetNuke and PHPNuke

41 21 Rich Internet Applications (RIAs) Rich Internet Applications (RIAs) Ajax Flex Web applications that offer the responsiveness, rich features and functionality approaching that of desktop applications Asynchronous JavaScript and XML Allows partial page Creates a more responsive GUI, allowing users to continue interacting with the page as the server processes requests Technologies that make up Ajax XHTML, CSS, JavaScript, the DOM, XML, and the XMLHttpRequest object RIA framework that allows you to build scalable, cross-platform, multimedia-rich applications that can be delivered over the Internet

42 22 Rich Internet Applications (RIAs) Silverlight Microsoft app formerly known as Windows Presentation Foundation Everywhere (WPF/E) Competitor to Flex and Flash Uses a compact version of the.net framework User interfaces built in Extensible Application Markup Language (XAML) Microsoft s XML-based format for describing user interfaces JavaFX Sun Microsystems counterpart to Flex and Silverlight Consists of the JavaFX Script and JavaFX Mobile (for mobile devices Ruby on Rails Open source framework based on the Ruby scripting language that allows you to build database-intensive applications quickly, easily, and with less code

43 23 Web Services, Widgets and Gadgets Incorporating web services into new programs allows people to develop new applications quickly Widgets and Gadgets Mini applications designed to run either as stand-alone applications or as add-on features in web pages Personalize your Internet experience by displaying real-time weather conditions, viewing maps, receiving event reminders, providing easy access to search engines and more. Amazon is a leading provider of web services

44 24 Location-Based Services Location-Based Services (LBS) Applications that take your geographic location (city, state, location of your mobile device, etc.) into consideration Global Positioning System (GPS) Local search Global Positioning System (GPS) Uses numerous satellites that send signals to a GPS receiver to determine its exact location. Mapping Services Google Maps is one of the most popular mapping applications available online. Google Earth provides satellite images of virtually any location on the planet MapQuest provides similar mapping services

45 25 XML, JSON and VoIP XML Extensible Markup Language that is a markup language that allows you to label data based on its meaning Describes data in a way that is meaningful to both humans and computers Document Type Definition (DTD), which defines the structure for the document JSON JavaScript Object Notation (JSON) Text-based data interchange format used to represent JavaScript objects as strings and transmit them over a network Commonly used in Ajax applications VoIP Voice over Internet Protocol (VoIP) is the technology used to make free or inexpensive phone calls over the Internet.

46 1 4 Introduction to XHTML

47 2 4.1 Introduction XHTML (Extensible HyperText Markup Language) markup language for creating web pages Based on HTML (HyperText Markup Language) legacy technology of the World Wide Web Consortium (W3C) XHTML 1.0 Allows only a document s content and structure to appear in a valid XHTML document, and not its formatting Formatting is specified with Cascading Style Sheets

48 3 4.3 First XHTML Example In XHTML, text is marked up with elements delimited by tags that are names contained in pairs of angle brackets Every XHTML document contains a start <html> tag and an end </html> tag Some elements may contain attributes that provide additional information about the element Comments in XHTML always begin with <!-- and end with -->. The browser ignores all text inside a comment

49 4 4.3 First XHTML Example (Cont.) Every XHTML document contains a head element which generally contains: A title A body element head element generally is not rendered in the display window

50 5 4.3 First XHTML Example (Cont.) The title element: Names a web page Usually appears in the colored bar (called the title bar) at the top of the browser window Is the text identifying a page when users add your page to their list of Favorites or Bookmarks The body element: Contains the document s content, which may include text and tags All text placed between the <p> and </p> tags forms one paragraph

51 6 4.3 First XHTML Example (Cont.) XHTML documents delimit an element with start and end tags A start tag consists of the element name in angle brackets (e.g., <html>) An end tag consists of the element name preceded by a forward slash (/) in angle brackets (e.g., </html>) Many start tags have attributes that provide additional information about an element Each attribute has a name and a value separated by an equals sign (=)

52 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 4.1: main.html --> 6 <!-- First XHTML example. --> 7 <html xmlns = " 8 <head> 9 <title>welcome</title> 10 </head> <body> 13 <p>welcome to XHTML!</p> 14 </body> 15 </html> XHTML comments, not interpreted by the browser Creates a head element Creates a title element, which contains the text Welcome Creates a p element within the body, which displays welcome text Fig. 4.1 First XHTML example Pearson Education, Inc. All rights reserved.

53 8 4.4 W3C XHTML Validation Service XHTML documents that are syntactically correct are guaranteed to render properly XHTML documents that contain syntax errors may not display properly Validation services (e.g., validator.w3.org) ensure that an XHTML document is syntactically correct

54 9 4.5 Headings XHTML provides six headings (h1 through h6) for specifying the relative importance of information Heading element h1 is considered the most significant heading and is rendered in the largest font Each successive heading element (i.e., h2, h3, etc.) is rendered in a progressively smaller font

55 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 4.2: heading.html --> 6 <!-- Heading elements h1 through h6. --> 7 <html xmlns = " 8 <head> 9 <title>headings</title> 10 </head> <body> 13 <h1>level 1 Heading</h1> 14 <h2>level 2 heading</h2> 15 <h3>level 3 heading</h3> 16 <h4>level 4 heading</h4> 17 <h5>level 5 heading</h5> 18 <h6>level 6 heading</h6> 19 </body> 20 </html> Creates six headings, each with decreasing significance Fig. 4.2 Heading elements h1 through h Pearson Education, Inc. All rights reserved.

56 Linking A hyperlink references or links to other resources, such as XHTML documents and images Web browsers typically underline text hyperlinks and color them blue by default

57 Linking (Cont.) Users can insert links with the a (anchor) element. The href attribute specifies the resource (e.g., page, file, e- mail address) being linked Anchors can link to an address using a mailto: URL When a user clicks this type of anchored link, most browsers launch the default program (e.g., Outlook Express) to initiate an message addressed to the linked address

58 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 4.3: links.html --> 6 <!-- Linking to other web pages. --> 7 <html xmlns = " 8 <head> 9 <title>links</title> 10 </head> <body> 13 <h1>here are my favorite sites</h1> 14 <p><strong>click a name to go to that page.</strong></p> <!-- Create four text hyperlinks --> 17 <p><a href = " 18 <p><a href = " Hall</a></p> 19 <p><a href = " 20 <p><a href = " Today</a></p> 21 </body> 22 </html> 4.3 Linking to other web pages. Creates anchor elements that link to the URL specified in the href attribute Pearson Education, Inc. All rights reserved.

59 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 4.4: contact.html --> 6 <!-- Linking to an address. --> 7 <html xmlns = " 8 <head> 9 <title>contact Page</title> 10 </head> <body> 13 <p> 14 My address is 15 <a href = "mailto:deitel@deitel.com"> 16 deitel@deitel.com 17 </a> 18. Click the address and your default client 19 will open an message and address it to me. 20 </p> 21 </body> 22 </html> Hyperlink that creates a message to the address deitel@deitel.com with the computer s default program 14 Fig. 4.4 Linking to an address (Part 1 of 2) Pearson Education, Inc. All rights reserved.

60 Images The img element s src attribute specifies an image s location Every img element must have an alt attribute, which contains text that is displayed if the client cannot render the image The alt attribute makes web pages more accessible to users with disabilities, especially vision impairments Width and height are optional attributes If omitted, the browser uses the image s actual width and height Images are measured in pixels

61 Images (Cont.) Some XHTML elements are empty elements that contain only attributes and do not mark up text Empty elements (e.g., img) must be terminated, either by using the forward slash character (/) inside the closing right angle bracket or by explicitly writing an end tag

62 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 4.5: picture.html --> 6 <!-- Images in XHTML files. --> 7 <html xmlns = " 8 <head> 9 <title>images</title> 10 </head> <body> 13 <p> 14 <img src = "cpphtp6.jpg" width = "92" height = "120" 15 alt = "C++ How to Program book cover" /> 16 <img src = "jhtp.jpg" width = "92" height = "120" 17 alt = "Java How to Program book cover" /> 18 </p> 19 </body> 20 </html> Specifies the image file s location Specifies the image s width 4.5 Images in XHTML files. Specifies the image s height Specifies text to display if the image is unavailable Pearson Education, Inc. All rights reserved.

63 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 4.6: nav.html --> 6 <!-- Images as link anchors. --> 7 <html xmlns = " 8 <head> 9 <title>navigation Bar</title> 10 </head> <body> 13 <p> 14 <a href = "links.html"> 15 <img src = "buttons/links.jpg" width = "65" 16 height = "50" alt = "Links Page" /> 17 </a> <a href = "list.html"> 20 <img src = "buttons/list.jpg" width = "65" 21 height = "50" alt = "List Example Page" /> 22 </a> <a href = "contact.html"> 25 <img src = "buttons/contact.jpg" width = "65" 26 height = "50" alt = "Contact Page" /> 27 </a> 28 Creates a hyperlinked image 18 Fig. 4.6 Images as link anchors (Part 1 of 2) Pearson Education, Inc. All rights reserved.

64 29 <a href = "table1.html"> 30 <img src = "buttons/table.jpg" width = "65" 31 height = "50" alt = "Table Page" /> 32 </a> <a href = "form.html"> 35 <img src = "buttons/form.jpg" width = "65" 36 height = "50" alt = "Feedback Form" /> 37 </a> 38 </p> 39 </body> 40 </html> Fig. 4.6 Images as link anchors (Part 1 of 2) Pearson Education, Inc. All rights reserved.

65 4.8 Special Characters and Horizontal Rules 20 XHTML provides special characters or entity references (in the form &code;) for representing characters that cannot be rendered otherwise The code can be: Word abbreviations Numbers Decimal Hexadecimal Example: & character represented by: &amp &#38 (decimal) &#x26 (hexadecimal)

66 4.8 Special Characters and Horizontal Rules (Cont.) 21 Most browsers render a horizontal rule, indicated by the <hr /> tag, as a horizontal line The hr element also inserts a line break above and below the horizontal line

67 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 4.7: contact2.html --> 6 <!-- Inserting special characters. --> 7 <html xmlns = " 8 <head> 9 <title>contact Page</title> 10 </head> <body> 13 <p> 14 Click 15 <a href = "mailto:deitel@deitel.com">here</a> 16 to open an message addressed to 17 deitel@deitel.com. 18 </p> <hr /> <!-- inserts a horizontal rule --> <!-- special characters are entered --> 23 <!-- using the form &code; --> 24 <p>all information on this site is <strong> 25 Deitel & Associates, Inc </strong></p> 26 Inserts a horizontal rule, with a line break before and after Inserts the special characters and & Fig. 4.7 Inserting special characters (Part 1 of 2) Pearson Education, Inc. All rights reserved.

68 27 <!-- to strike through text use <del> tags --> Creates a strikethrough effect 28 <!-- to subscript text use <sub> tags --> 29 <!-- to superscript text use <sup> tags --> 30 <!-- these tags are nested inside other tags --> 31 <p><del>you may download 3.14 x 10<sup>2</sup> 32 characters worth of information from this site.</del> 33 Only <sub>one</sub> download per hour is permitted.</p> 34 <p><em>note: < ¼ of the information 35 presented here is updated daily.</em></p> 36 </body> 37 </html> Emphasizes text Makes the 1 subscript Inserts the special symbols < and ¼ Makes the 2 superscript Fig. 4.7 Inserting special characters (Part 2 of 2) Pearson Education, Inc. All rights reserved.

69 Lists Unordered list element ul creates a list in which each item in the list begins with a bullet symbol (called a disc) Each entry is an li (list item) element. Most web browsers render these elements with a line break and a bullet symbol at the beginning of the line

70 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 4.8: links2.html --> 6 <!-- Unordered list containing hyperlinks. --> 7 <html xmlns = " 8 <head> 9 <title>links</title> 10 </head> <body> 13 <h1>here are my favorite sites</h1> 14 <p><strong>click on a name to go to that page.</strong></p> <!-- create an unordered list --> 17 <ul> 18 <!-- add four list items --> 19 <li><a href = " 20 <li><a href = " 21 <li><a href = " 22 <li><a href = " 23 </ul> 24 </body> 25 </html> Creates an unordered list Makes hyperlinked elements into individual list items Fig. 4.8 Unordered list containing hyperlinks (Part 1 of 2) Pearson Education, Inc. All rights reserved.

71 26 Fig. 4.8 Unordered list containing hyperlinks (Part 2 of 2).

72 Lists (Cont.) The ordered list element ol creates a list in which each item begins with a number Lists may be nested to represent hierarchical data relationships

73 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 4.9: list.html --> 6 <!-- Nested and ordered lists. --> 7 <html xmlns = " 8 <head> 9 <title>lists</title> 10 </head> <body> 13 <h1>the Best Features of the Internet</h1> <!-- create an unordered list --> 16 <ul> 17 <li>you can meet new people from countries around 18 the world.</li> 19 <li> 20 You have access to new media as it becomes public: <!-- this starts a nested list, which uses a --> 23 <!-- modified bullet. The list ends when you --> 24 <!-- close the <ul> tag. --> 25 <ul> 26 <li>new games</li> 27 <li>new applications 28 A single list element Fig. 4.9 Nested and ordered lists (Part 1 of 3) Pearson Education, Inc. All rights reserved.

74 29 <!-- nested ordered list --> 30 <ol> 31 <li>for business</li> 32 <li>for pleasure</li> 33 </ol> 34 </li> <!-- ends line 27 new applications li --> <li>around the clock news</li> 37 <li>search engines</li> 38 <li>shopping</li> 39 <li>programming <!-- another nested ordered list --> 42 <ol> 43 <li>xml</li> 44 <li>java</li> 45 <li>xhtml</li> 46 <li>scripts</li> 47 <li>new languages</li> 48 </ol> 49 </li> <!-- ends programming li of line 39 --> 50 </ul> <!-- ends the nested list of line 25 --> 51 </li> <li>links</li> 54 <li>keeping in touch with old friends</li> 55 <li>it is the technology of the future!</li> 56 </ul> <!-- ends the unordered list of line 16 --> 57 </body> 58 </html> Creates an ordered list within a list element Ends nested list Ends the list element Another single unordered list element Creates an ordered list within this list element Fig. 4.9 Nested and ordered lists (Part 2 of 3) Pearson Education, Inc. All rights reserved.

75 30 Fig. 4.9 Nested and ordered lists (Part 3 of 3).

76 Tables table element defines an XHTML table Attribute summary summarizes the table s contents and is used by speech devices to make the table more accessible to users with visual impairments Element caption describes the table s content The text inside the <caption> tag is rendered above the table in most browsers

77 Tables (Cont.) A table can be split into three distinct sections: Head (thead element) Table titles Column headers Body (tbody element) Primary table data Foot (tfoot element) Calculation results Footnotes Above body section in the code, but displays at the bottom in the page

78 Tables (Cont.) Element tr Defines individual table rows Element th Defines a header cell Element td Contains table data elements

79 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 4.10: table1.html --> 6 <!-- Creating a basic table. --> 7 <html xmlns = " 8 <head> 9 <title>a simple XHTML table</title> 10 </head> <body> <!-- the <table> tag opens a table --> 15 <table border = "1" width = "40%" 16 summary = "This table provides information about 17 the price of fruit"> <!-- the <caption> tag summarizes the table's --> 20 <!-- contents (this helps the visually impaired) --> 21 <caption><strong>price of Fruit</strong></caption> <!-- the <thead> section appears first in the table --> 24 <!-- it formats the table header area --> 25 <thead> 26 <tr> <!-- <tr> inserts a table row --> 27 <th>fruit</th> <!-- insert a heading cell --> 28 <th>price</th> 29 </tr> 30 </thead> 31 Begins a new XHTML table Sets the table s border to be one pixel wide Sets the table s width to 40% of the screen Describes the table s contents in the summary attribute Sets the text above the table Creates a head element Creates a table heading cell in the new table row 4.10 Creating a basic table (Part 1 of 3). 34 Makes a new table row Creates the next cell in the row 2008 Pearson Education, Inc. All rights reserved.

80 32 <!-- the <tfoot> section appears last in the table --> 33 <!-- it formats the table footer --> 34 <tfoot> 35 <tr> 36 <th>total</th> 37 <th>$3.75</th> 38 </tr> 39 </tfoot> <!-- all table content is enclosed --> 42 <!-- within the <tbody> --> 43 <tbody> 44 <tr> 45 <td>apple</td> <!-- insert a data cell --> 46 <td>$0.25</td> 47 </tr> 48 <tr> 49 <td>orange</td> 50 <td>$0.50</td> 51 </tr> 52 <tr> 53 <td>banana</td> 54 <td>$1.00</td> 55 </tr> 56 <tr> 57 <td>pineapple</td> 58 <td>$2.00</td> 59 </tr> 60 </tbody> 61 </table> </body> 64 </html> Creates a foot section Creates table header cells at the bottom of the table Creates a body section Ends the table Inserts a cell in the body of the table 4.10 Creating a basic table (Part 2 of 3) Pearson Education, Inc. All rights reserved.

81 Creating a basic table (Part 3 of 3).

82 Tables (Cont.) You can merge data cells with the rowspan and colspan attributes The values of these attributes specify the number of rows or columns occupied by the cell Can be placed inside any data cell or table header cell

83 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 4.11: table2.html --> 6 <!-- Complex XHTML table. --> 7 <html xmlns = " 8 <head> 9 <title>tables</title> 10 </head> <body> 13 <h1>table Example Page</h1> <table border = "1"> 16 <caption>here is a more complex sample table.</caption> <thead> 19 <!-- rowspans and colspans merge the specified --> 20 <!-- number of cells vertically or horizontally --> 21 <tr> 22 <!-- merge two rows --> 23 <th rowspan = "2"> 24 <img src = "camel.gif" width = "205" 25 height = "167" alt = "Picture of a camel" /> 26 </th> 27 Makes the header cell span 2 rows 4.11 Complex XHTML table (Part 1 of 3) Pearson Education, Inc. All rights reserved.

84 28 <!-- merge four columns --> 29 <th colspan = "4"> 30 <h1>camelid comparison</h1> 31 <p>approximate as of 6/2007</p> 32 </th> 33 </tr> 34 <tr> 35 <th># of Humps</th> 36 <th>indigenous region</th> 37 <th>spits?</th> 38 <th>produces Wool?</th> 39 </tr> 40 </thead> 41 <tbody> 42 <tr> 43 <th>camels (bactrian)</th> 44 <td>2</td> 45 <td>africa/asia</td> 46 <td>yes</td> 47 <td>yes</td> 48 </tr> 49 <tr> 50 <th>llamas</th> 51 <td>1</td> 52 <td>andes Mountains</td> 53 <td>yes</td> 54 <td>yes</td> 55 </tr> 56 </tbody> 57 </table> 58 </body> 59 </html> Makes the header cell span 4 columns 4.11 Complex XHTML table (Part 2 of 3) Pearson Education, Inc. All rights reserved.

85 Complex XHTML table (Part 3 of 3).

86 Forms XHTML provides forms for collecting information from users Forms contain visual components, such as buttons, that users interact with Forms may also contain nonvisual components, called hidden inputs, which are used to store any data that needs to be sent to the server, but is not entered by the user

87 Forms (Cont.) A form begins with the form element Attribute method specifies how the form s data is sent to the web server The action attribute of the form element specifies the script to which the form data will be sent

88 Forms (Cont.) The input element provides data to the script that processes the form The text input inserts a text box into the form, which allows the user to input data The label element provides users with information about the input element s purpose The size attribute specifies the number of characters visible in the input element Optional attribute maxlength limits the number of characters input into a text box The submit input submits the data entered in the form to the web server for processing Most web browsers create a button that submits the form data when clicked The reset input allows a user to reset all form elements to their default values

89 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 4.12: form.html --> 6 <!-- Form with hidden fields and a text box. --> 7 <html xmlns = " 8 <head> 9 <title>forms</title> 10 </head> <body> 13 <h1>feedback Form</h1> <p>please fill out this form to help 16 us improve our site.</p> <!-- this tag starts the form, gives the --> 19 <!-- method of sending information and the --> 20 <!-- location of form script --> 21 <form method = "post" action = ""> 22 <p> 23 <!-- hidden inputs contain non-visual --> 24 <!-- information --> 25 <input type = "hidden" name = "recipient" 26 value = "deitel@deitel.com" /> 27 <input type = "hidden" name = "subject" 28 value = "Feedback Form" /> 29 <input type = "hidden" name = "redirect" 30 value = "main.html" /> 31 </p> Appends form data to the browser request No URL is used to process this form s data Creates hidden inputs not visible to the user Fig Form with hidden fields and a text box (Part 1 of 2) Pearson Education, Inc. All rights reserved.

90 32 33 <!-- <input type = "text"> inserts a text box --> 34 <p><label>name: 35 <input name = "name" type = "text" size = "25" 36 maxlength = "30" /> 37 </label></p> <p> 40 <!-- input types "submit" and "reset" insert --> 41 <!-- buttons for submitting and clearing the --> 42 <!-- form's contents --> 43 <input type = "submit" value = "Submit" /> 44 <input type = "reset" value = "Clear" /> 45 </p> 46 </form> 47 </body> 48 </html> Ends the XHTML form Creates a label for the text field Inserts a text box called name with 25 characters visible and a 30 character limit Inserts a submit button with Submit written on it Inserts a reset button with Clear written on it Fig Form with hidden fields and a text box (Part 2 of 2) Pearson Education, Inc. All rights reserved.

91 Forms (Cont.) The textarea element inserts a multiline text box, called a text area, into a form The number of rows in the text area is specified with the rows attribute The number of columns (i.e., characters per line) is specified with the cols attribute The password input inserts a password box into a form Allows users to enter sensitive information, such as credit card numbers and passwords, by masking the information input with another character, usually asterisks The actual value input is sent to the web server, not the asterisks that mask the input

92 Forms (Cont.) The checkbox input allows the user to make a selection When the checkbox is selected, a check mark appears in the checkbox. Otherwise, the checkbox is empty Checkboxes can be used individually and in groups. Checkboxes that are part of the same group have the same name A radio button is similar in function and use to a checkbox, except that only one radio button in a group can be selected at any time All radio buttons in a group have the same name attribute but different value attributes. The select input provides a drop-down list of items The name attribute identifies the drop-down list The option element adds items to the drop-down list

93 Forms (Cont.) The br element causes most browsers to render a line break Any markup or text following a br element is rendered on the next line

94 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 4.13: form2.html --> 6 <!-- Form using a variety of components. --> 7 <html xmlns = " 8 <head> 9 <title>more Forms</title> 10 </head> <body> 13 <h1>feedback Form</h1> 14 <p>please fill out this form to help 15 us improve our site.</p> <form method = "post" action = ""> 18 <p> 19 <input type = "hidden" name = "recipient" 20 value = "deitel@deitel.com" /> 21 <input type = "hidden" name = "subject" 22 value = "Feedback Form" /> 23 <input type = "hidden" name = "redirect" 24 value = "main.html" /> 25 </p> <p><label>name: 28 <input name = "name" type = "text" size = "25" /> 29 </label></p> 30 Fig Form using a variety of components (Part 1 of 5) Pearson Education, Inc. All rights reserved.

95 31 <!-- <textarea> creates a multiline textbox --> 32 <p><label>comments:<br /> 33 <textarea name = "comments" 34 rows = "4" cols = "36">Enter comments here.</textarea> 35 </label></p> <!-- <input type = "password"> inserts a --> 38 <!-- textbox whose display is masked with --> 39 <!-- asterisk characters --> 40 <p><label> Address: 41 <input name = " " type = "password" size = "25" /> 42 </label></p> <p> 45 <strong>things you liked:</strong><br /> <label>site design 48 <input name = "thingsliked" type = "checkbox" 49 value = "Design" /></label> 50 <label>links 51 <input name = "thingsliked" type = "checkbox" 52 value = "Links" /></label> 53 <label>ease of use 54 <input name = "thingsliked" type = "checkbox" 55 value = "Ease" /></label> 56 <label>images 57 <input name = "thingsliked" type = "checkbox" 58 value = "Images" /></label> 59 <label>source code 60 <input name = "thingsliked" type = "checkbox" 61 value = "Code" /></label> 62 </p> Inserts a text area with 4 rows and 36 columns, whose initial text is Enter comments here. Inserts an input field that displays entered text as asterisks (or another character) Fig Form using a variety of components (Part 2 of 5). Inserts several checkboxes with different labels Pearson Education, Inc. All rights reserved.

96 63 64 <!-- <input type = "radio" /> creates a radio --> 65 <!-- button. The difference between radio buttons --> 66 <!-- and checkboxes is that only one radio button --> 67 <!-- in a group can be selected. --> 68 <p> 69 <strong>how did you get to our site?:</strong><br /> <label>search engine 72 <input name = "howtosite" type = "radio" 73 value = "search engine" checked = "checked" /></label> 74 <label>links from another site 75 <input name = "howtosite" type = "radio" 76 value = "link" /></label> 77 <label>deitel.com Website 78 <input name = "howtosite" type = "radio" 79 value = "deitel.com" /></label> 80 <label>reference in a book 81 <input name = "howtosite" type = "radio" 82 value = "book" /></label> 83 <label>other 84 <input name = "howtosite" type = "radio" 85 value = "other" /></label> 86 </p> <p> 89 <label>rate our site: 90 Initially sets this radio button as selected Fig Form using a variety of components (Part 3 of 5). Inserts a group of radio buttons, only one of which can be selected Pearson Education, Inc. All rights reserved.

97 91 <!-- the <select> tag presents a drop-down --> 92 <!-- list with choices indicated by the --> 93 <!-- <option> tags --> 94 <select name = "rating"> 95 <option selected = "selected">amazing</option> 96 <option>10</option> 97 <option>9</option> 98 <option>8</option> 99 <option>7</option> 100 <option>6</option> 101 <option>5</option> 102 <option>4</option> 103 <option>3</option> 104 <option>2</option> 105 <option>1</option> 106 <option>awful</option> 107 </select> 108 </label> 109 </p> <p> 112 <input type = "submit" value = "Submit" /> 113 <input type = "reset" value = "Clear" /> 114 </p> 115 </form> 116 </body> 117 </html> Create a drop-down list named Fig Form rating using a variety of components (Part 4 of 5). Sets Amazing as the initially selected option Pearson Education, Inc. All rights reserved.

98 53 Fig Form using a variety of components (Part 5 of 5).

99 Internal Linking The a tag can be used to link to another section of the same document by specifying the element s id as the link s href. To link internally to an element with its id attribute set, use the syntax #id.

100 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 4.14: internal.html --> 6 <!-- Internal hyperlinks to make pages more navigable. --> 7 <html xmlns = " 8 <head> 9 <title>internal Links</title> 10 </head> <body> 13 <!-- id attribute creates an internal hyperlink destination --> 14 <h1 id = "features">the Best Features of the Internet</h1> <!-- an internal link's address is "#id" --> 17 <p><a href = "#bugs">go to <em>favorite Bugs</em></a></p> <ul> 20 <li>you can meet people from countries 21 around the world.</li> 22 <li>you have access to new media as it becomes public: 23 <ul> 24 <li>new games</li> 25 <li>new applications 26 <ul> 27 <li>for Business</li> 28 <li>for Pleasure</li> 29 </ul> 30 </li> 31 Sets the id attribute for the h1 element Fig Internal hyperlinks to make pages more navigable (Part 1 of 3). Creates a link to the element in this document with id = bugs Pearson Education, Inc. All rights reserved.

101 32 <li>around the clock news</li> 33 <li>search Engines</li> 34 <li>shopping</li> 35 <li>programming 36 <ul> 37 <li>xhtml</li> 38 <li>java</li> 39 <li>dynamic HTML</li> 40 <li>scripts</li> 41 <li>new languages</li> 42 </ul> 43 </li> 44 </ul> 45 </li> <li>links</li> 48 <li>keeping in touch with old friends</li> 49 <li>it is the technology of the future!</li> 50 </ul> <!-- id attribute creates an internal hyperlink destination --> 53 <h1 id = "bugs">my 3 Favorite Bugs</h1> 54 <p> 55 <!-- internal hyperlink to features --> 56 <a href = "#features">go to <em>favorite Features</em></a> 57 </p> 58 <ol> 59 <li>fire Fly</li> 60 <li>gal Ant</li> 61 <li>roman Tic</li> 62 </ol> 63 </body> 64 </html> Sets the id attribute for this h1 element Fig Internal hyperlinks to make pages more navigable (Part 2 of 3). Creates a link to the element in this document with id = features Pearson Education, Inc. All rights reserved.

102 57 Fig Internal hyperlinks to make pages more navigable (Part 3 of 3).

103 meta Elements One way that search engines catalog pages is by reading the meta element s contents. The name attribute identifies the type of meta element The content attribute Of a keywords meta element: provides search engines with a list of words that describe a page, which are compared with words in search requests Of a description meta element: provides a three- to four-line description of a site in sentence form, used by search engines to catalog your site. This text is sometimes displayed as part of the search result

104 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 4.15: meta.html --> 6 <!-- meta elements provide keywords and a description of a page. --> 7 <html xmlns = " 8 <head> 9 <title>welcome</title> <!-- <meta> tags provide search engines with --> 12 <!-- information used to catalog a site --> 13 <meta name = "keywords" content = "web page, design, 14 XHTML, tutorial, personal, help, index, form, 15 contact, feedback, list, links, deitel" /> 16 <meta name = "description" content = "This website will 17 help you learn the basics of XHTML and web page design 18 through the use of interactive examples and 19 instruction." /> 20 </head> 21 <body> 22 <h1>welcome to Our Website!</h1> <p>we have designed this site to teach about the wonders 25 of <strong><em>xhtml</em></strong>. <em>xhtml</em> is 26 better equipped than <em>html</em> to represent complex 27 data on the Internet. <em>xhtml</em> takes advantage of 28 XML s strict syntax to ensure well-formedness. Soon you 29 will know about many of the great features of 30 <em>xhtml.</em></p> <p>have Fun With the Site!</p> 33 </body> 34 </html> Fig meta elements provide keywords and a description of a page (Part 1 of 2). Provides keywords describing the page for a search engine Provides the site s description in sentence form for a search engine Pearson Education, Inc. All rights reserved.

105 60 Fig meta elements provide keywords and a description of a page (Part 2 of 2).

106 1 5 Cascading Style Sheets (CSS)

107 2 5.1 Introduction Cascading Style Sheets (CSS) Used to specify the presentation of elements separately from the structure of the document CSS validator jigsaw.w3.org/css-validator/

108 3 5.2 Inline Styles Inline style declare a style for an individual element by using the style attribute in the element s start tag Each CSS property is followed by a colon and the value of the attribute Multiple property declarations are separated by a semicolon color property sets text color Color names and hexadecimal codes may be used as the value

109 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 5.1: inline.html --> 6 <!-- Using inline styles --> 7 <html xmlns = " 8 <head> 9 <title>inline Styles</title> 10 </head> 11 <body> 12 <p>this text does not have any style applied to it.</p> <!-- The style attribute allows you to declare --> 15 <!-- inline styles. Separate multiple style properties --> 16 <!-- with a semicolon. --> 17 <p style = "font-size: 20pt">This text has the 18 <em>font-size</em> style applied to it, making it 20pt. 19 </p> <p style = "font-size: 20pt; color: #6666ff"> 22 This text has the <em>font-size</em> and 23 <em>color</em> styles applied to it, making it 24 20pt. and light blue.</p> 25 </body> 26 </html> Style attribute Sets the paragraph s font size to 20pt Sets the paragraph s color to light blue Fig. 5.1 Using inline styles (Part 1 of 2) Pearson Education, Inc. All rights reserved.

110 5 Fig. 5.1 Using inline styles (Part 2 of 2).

111 6 5.3 Embedded Style Sheets Styles that are placed in a style element use selectors to apply style elements throughout the entire document style element attribute type specifies the MIME type (the specific encoding format) of the style sheet. Style sheets use text/css Each rule body in a style sheet begins and ends with a curly brace ({ and }).

112 7 5.3 Embedded Style Sheets (Cont.) Style-class declarations are preceded by a period and are applied to elements of the specific class The class attribute applies a style class to an element CSS rules in a style sheet use the same format as inline styles: The property is followed by a colon (:) and the value of that property Multiple properties are separated by semicolons (;)

113 8 5.3 Embedded Style Sheets (Cont.) font-weight property specifies the boldness of text. Possible values are: bold normal (the default) bolder (bolder than bold text) lighter (lighter than normal text) Boldness also can be specified with multiples of 100, from 100 to 900 (e.g., 100, 200,, 900). Text specified as normal is equivalent to 400, and bold text is equivalent to 700

114 9 5.3 Embedded Style Sheets (Cont.) background-color attribute specifies the background color of the element font-family attribute names a specific font that should be displayed Generic font families allow authors to specify a type of font instead of a specific font, in case a browser does not support a specific font font-size property specifies the size used to render the font

115 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 5.2: embedded.html --> 6 <!-- Embedded style sheets. --> 7 <html xmlns = " 8 <head> 9 <title>style Sheets</title> <!-- this begins the style sheet section --> 12 <style type = "text/css"> 13 em { font-weight: bold; 14 color: black } 15 h1 { font-family: tahoma, helvetica, sans-serif } 16 p { font-size: 12pt; 17 font-family: arial, sans-serif } 18.special { color: #6666ff } 19 </style> 20 </head> 21 <body> 22 <!-- this class attribute applies the.special style --> 23 <h1 class = "special">deitel & Associates, Inc.</h1> <p>deitel & Associates, Inc. is an internationally 26 recognized corporate training and publishing organization 27 specializing in programming languages, Internet/World 28 Wide Web technology and object technology education. 29 The company provides courses on Java, C++, Visual Basic, 30 C#, C, Internet and World Wide Web programming, Object 31 Technology, and more.</p> Sets the properties for all elements in the document within em tags Sets the properties for all h1 elements in the document Sets the properties for all p elements in the document Style sheet ends Creates a special class Fig. 5.2 Embedded style sheets (Part 1 of 2) Pearson Education, Inc. All rights reserved.

116 32 33 <h1>clients</h1> 34 <p class = "special"> The company's clients include many 35 <em>fortune 1000 companies</em>, government agencies, 36 branches of the military and business organizations. 37 Through its publishing partnership with Prentice Hall, 38 Deitel & Associates, Inc. publishes leading-edge 39 programming textbooks, professional books, interactive 40 web-based multimedia Cyber Classrooms, satellite 41 courses and World Wide Web courses.</p> 42 </body> 43 </html> The special class is applied to this p element Fig. 5.2 Embedded style sheets (Part 2 of 2) Pearson Education, Inc. All rights reserved.

117 Conflicting Styles Styles defined by the user take precedence over styles defined by the user agent Styles defined by authors take precedence over styles defined by the user Most styles are inherited from parent elements. Styles defined for children have higher specificity and take precedence over the parent s styles Conflicts are resolved in favor of properties with a higher specificity

118 Conflicting Styles (Cont.) text-decoration property applies decorations to text in an element underline overline line-through blink

119 Conflicting Styles (Cont.) Pseudoclasses give the author access to content not specifically declared in the document Pseudoclasses are separated by a colon (with no surrounding spaces) from the name of the element to which they are applied hover pseudoclass is activated when the user moves the mouse cursor over an element

120 Conflicting Styles (Cont.) To apply rules to multiple elements, separate the elements with commas in the style sheet To apply rules to only a certain type of element that is a child of another type, separate the element names with spaces

121 Conflicting Styles (Cont.) Relative length measurements: px (pixels size varies depending on screen resolution) em (usually the height of a font s uppercase M) ex (usually the height of a font s lowercase x) Percentages (of the font s default size) Absolute-length measurements (units that do not vary in size): in (inches) cm (centimeters) mm (millimeters) pt (points; 1 pt = 1/72 in) pc (picas; 1 pc = 12 pt)

122 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 5.3: advanced.html --> 6 <!-- Inheritance in style sheets. --> 7 <html xmlns = " 8 <head> 9 <title>more Styles</title> 10 <style type = "text/css"> 11 body { font-family: arial, helvetica, sans-serif } 12 a.nodec { text-decoration: none } 13 a:hover { text-decoration: underline } 14 li em { font-weight: bold } 15 h1, em { text-decoration: underline } 16 ul { margin-left: 20px } 17 ul ul { font-size:.8em } 18 </style> 19 </head> 20 <body> 21 <h1>shopping list for Monday:</h1> 22 Defines the class nodec that can only be used by anchor elements Sets the properties for the hover pseudoclass for the a element, which is activated when the user moves the cursor over an anchor element All em elements that are children of li elements set to bold Applies underline style to all h1 and em elements Fig. 5.3 Inheritance in style sheets (Part 1 of 3) Pearson Education, Inc. All rights reserved.

123 23 <ul> 24 <li>milk</li> 25 <li>bread 26 <ul> 27 <li>white bread</li> 28 <li>rye bread</li> 29 <li>whole wheat bread</li> 30 </ul> 31 </li> 32 <li>rice</li> 33 <li>potatoes</li> 34 <li>pizza <em>with mushrooms</em></li> 35 </ul> <p><em>go to the</em> 38 <a class = "nodec" href = " 39 Grocery store</a> 40 </p> 41 </body> 42 </html> Fig. 5.3 Inheritance in style sheets (Part 2 of 3) Pearson Education, Inc. All rights reserved.

124 19 Fig. 5.3 Inheritance in style sheets (Part 3 of 3).

125 Linking External Style Sheets External style sheets are separate documents that contain only CSS rules Help create a uniform look for a website separate pages can all use the same styles Modifying a single style-sheet file makes changes to styles across an entire website

126 Linking External Style Sheets (Cont.) link element Uses rel attribute to specify a relationship between two documents rel attribute declares the linked document to be a stylesheet for the document type attribute specifies the MIME type of the related document href attribute provides the URL for the document containing the style sheet

127 1 /* Fig. 5.4: styles.css */ 2 /* External stylesheet */ 3 4 body { font-family: arial, helvetica, sans-serif } 5 6 a.nodec { text-decoration: none } 7 8 a:hover { text-decoration: underline } 9 10 li em { font-weight: bold } h1, em { text-decoration: underline } ul { margin-left: 20px } ul ul { font-size:.8em; } Fig. 5.4 External style sheet Pearson Education, Inc. All rights reserved.

128 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 5.6: external.html --> 6 <!-- Linking an external style sheet. --> 7 <html xmlns = " 8 <head> 9 <title>linking External Style Sheets</title> 10 <link rel = "stylesheet" type = "text/css" 11 href = "styles.css" /> 12 </head> 13 <body> 14 <h1>shopping list for <em>monday</em>:</h1> <ul> 17 <li>milk</li> 18 <li>bread 19 <ul> 20 <li>white bread</li> 21 <li>rye bread</li> 22 <li>whole wheat bread</li> 23 </ul> 24 </li> 25 <li>rice</li> 26 <li>potatoes</li> 27 <li>pizza <em>with mushrooms</em></li> 28 </ul> 29 The linked document is declared to be the current one s stylesheet The linked document s MIME type is text/css The linked document s URL is styles.css Fig. 5.5 Linking an external style sheet (Part 1 of 2) Pearson Education, Inc. All rights reserved.

129 30 <p><em>go to the</em> 31 <a class = "nodec" href = " 32 Grocery store</a> 33 </p> 34 </body> 35 </html> Fig. 5.5 Linking an external style sheet (Part 2 of 2) Pearson Education, Inc. All rights reserved.

130 Positioning Elements CSS position property Allows absolute positioning, which provides greater control over where on a page elements reside Normally, elements are positioned on the page in the order that they appear in the XHTML document Specifying an element s position as absolute removes it from the normal flow of elements on the page and positions it according to distance from the top, left, right or bottom margin of its parent element

131 Positioning Elements (Cont.) The z-index property allows a developer to layer overlapping elements Elements that have higher z-index values are displayed in front of elements with lower z-index values

132 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 5.6: positioning.html --> 6 <!-- Absolute positioning of elements. --> 7 <html xmlns = " 8 <head> 9 <title>absolute Positioning</title> 10 <style type = "text/css"> 11.bgimg { position: absolute; 12 top: 0px; 13 left: 0px; 14 z-index: 1 } 15.fgimg { position: absolute; 16 top: 25px; 17 left: 100px; 18 z-index: 2 } 19.text { position: absolute; 20 top: 25px; 21 left: 100px; 22 z-index: 3; 23 font-size: 20pt; 24 font-family: tahoma, geneva, sans-serif } 25 </style> 26 </head> 27 <body> 28 <p><img src = "bgimg.gif" class = "bgimg" 29 alt = "First positioned image" /></p> 30 Class that sets an element s absolute position at the top left of the containing element Lowest z-index, so this element is behind all the others Set element s position 25px from the top and 100 from the left This element will appear on top of the first one, since it has a higher z-index This element will appear on top of all others, since it has the highest z-index Fig. 5.6 Absolute positioning of elements (Part 1 of 2) Pearson Education, Inc. All rights reserved.

133 31 <p><img src = "fgimg.gif" class = "fgimg" 32 alt = "Second positioned image" /></p> <p class = "text">positioned Text</p> 35 </body> 36 </html> Fig. 5.6 Absolute positioning of elements (Part 2 of 2) Pearson Education, Inc. All rights reserved.

134 Positioning Elements (Cont.) Relative positioning keeps elements in the general flow on the page and offsets them by the specified top, left, right or bottom value

135 Positioning Elements (Cont.) Inline-level elements Do not change the flow of the document Examples: img a em strong span Grouping element Does not apply any formatting to its contents Creates a container for CSS rules or id attributes to be applied to a section

136 Positioning Elements (Cont.) Block-level elements Displayed on their own line Have virtual boxes around them Examples: p all headings (h1 through h6) div A grouping element like span

137 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 5.7: positioning2.html --> 6 <!-- Relative positioning of elements. --> 7 <html xmlns = " 8 <head> 9 <title>relative Positioning</title> 10 <style type = "text/css"> 11 p { font-size: 1.3em; 12 font-family: verdana, arial, sans-serif } 13 span { color: red; 14 font-size:.6em; 15 height: 1em } 16.super { position: relative; 17 top: -1ex } 18.sub { position: relative; 19 bottom: -1ex } 20.shiftleft { position: relative; 21 left: -1ex } 22.shiftright { position: relative; 23 right: -1ex } 24 </style> 25 </head> 26 <body> 27 <p>the text at the end of this sentence 28 <span class = "super">is in superscript</span>.</p> 29 Positions element 5 ex upwards Positions element 1 ex downwards Positions element 1 ex to the left Positions element 1 ex to the right Fig. 5.7 Relative positioning of elements (Part 1 of 2). Apply the super class to this span element Pearson Education, Inc. All rights reserved.

138 30 <p>the text at the end of this sentence 31 <span class = "sub">is in subscript</span>.</p> <p>the text at the end of this sentence 34 <span class = "shiftleft">is shifted left</span>.</p> <p>the text at the end of this sentence 37 <span class = "shiftright">is shifted right</span>.</p> 38 </body> 39 </html> Apply the sub class to this span element Apply the shiftleft class to this span element Apply the shiftright class to this span element 33 Fig. 5.7 Relative positioning of elements (Part 2 of 2) Pearson Education, Inc. All rights reserved.

139 Backgrounds CSS can control the backgrounds of block-level elements by adding: Colors Images

140 Backgrounds (Cont.) Property background-image Specifies the URL of the image, in the format url(filelocation) Property background-position Places the image on the page using the values top, bottom, center, left and right individually or in combination for vertical and horizontal positioning. You can also position by using lengths

141 Backgrounds (Cont.) Property background-image specifies the URL of the image Use the format url(filelocation) Property background-position places the image on the page Use the values top, bottom, center, left and right individually or in combination for vertical and horizontal positioning You can also position by specifying horizontal then vertical distances from the top-left corner of the screen

142 Backgrounds (Cont.) background-repeat property controls the tiling of the background image Setting the tiling to no-repeat displays one copy of the background image on screen Setting to repeat (the default) tiles the image vertically and horizontally Setting to repeat-x tiles the image only horizontally Setting to repeat-y tile the image only vertically

143 Backgrounds (Cont.) Property setting background-attachment: fixed fixes the image in the position specified by backgroundposition. Scrolling the browser window will not move the image from its set position. The default value, scroll, moves the image as the user scrolls the window

144 Backgrounds (Cont.) text-indent property indents the first line of text in the element by the specified amount font-style property allows you to set text to none, italic or oblique

145 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 5.8: background.html --> 6 <!-- Adding background images and indentation. --> 7 <html xmlns = " 8 <head> 9 <title>background Images</title> 10 <style type = "text/css"> 11 body { background-image: url(logo.gif); 12 background-position: bottom right; 13 background-repeat: no-repeat; 14 background-attachment: fixed; 15 background-color: #eeeeee } 16 p { font-size: 18pt; 17 color: #1144AA; 18 text-indent: 1em; 19 font-family: arial, sans-serif; } 20.dark { font-weight: bold } 21 </style> 22 </head> Inserts the image at logo.gif as the background Places the image at the bottom right of the page Displays only one copy of the image Keeps the image in place when the user scrolls in the browser window Fills the remainder of the window with a light gray background 40 Fig. 5.8 Adding background images and indentation (Part 1 of 2). Indents the first line of text in the element by 1 em 2008 Pearson Education, Inc. All rights reserved.

146 23 <body> 24 <p> 25 This example uses the background-image, 26 background-position and background-attachment 27 styles to place the <span class = "dark">deitel 28 & Associates, Inc.</span> logo in the bottom, 29 right corner of the page. Notice how the logo 30 stays in the proper position when you resize the 31 browser window. The background-color fills in where 32 there is no image. 33 </p> 34 </body> 35 </html> Fig. 5.8 Adding background images and indentation (Part 2 of 2) Pearson Education, Inc. All rights reserved.

147 Element Dimensions Dimensions of elements on a page can be set with CSS by using properties height and width Their values can be relative or absolute Text in an element can be centered using textalign: center; other values for the text-align property are left and right

148 Element Dimensions (Cont.) Problem with setting both vertical and horizontal dimensions of an element Content might sometimes exceed the set boundaries, in which case the element must be made large enough for all the content to fit Can set the overflow property to scroll, which adds scroll bars if the text overflows the boundaries set for it

149 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 5.9: width.html --> 6 <!-- Element dimensions and text alignment. --> 7 <html xmlns = " 8 <head> 9 <title>box Dimensions</title> 10 <style type = "text/css"> 11 div { background-color: #aaccff; 12 margin-bottom:.5em; 13 font-family: arial, helvetica, sans-serif } 14 </style> 15 </head> 16 <body> 17 <div style = "width: 20%">Here is some 18 text that goes in a box which is 19 set to stretch across twenty percent 20 of the width of the screen.</div> <div style = "width: 80%; text-align: center"> 23 Here is some CENTERED text that goes in a box 24 which is set to stretch across eighty percent of 25 the width of the screen.</div> 26 Sets the width of the element to 20% of the browser s screen s size Fig. 5.9 Element dimensions and text alignment (Part 1 of 2). Sets the width of the element to 80% of the browser s screen s size and centers it Pearson Education, Inc. All rights reserved.

150 27 <div style = "width: 20%; height: 150px; overflow: scroll"> 28 This box is only twenty percent of 29 the width and has a fixed height. 30 What do we do if it overflows? Set the 31 overflow property to scroll!</div> 32 </body> 33 </html> Sets the width of the element to 20% of the browser s screen s size, the height to 150 px, and allows the element to scroll if the text overflows the allotted size Fig. 5.9 Element dimensions and text alignment (Part 2 of 2) Pearson Education, Inc. All rights reserved.

151 Box Model and Text Flow Block-level XHTML elements have a virtual box drawn around them based on the box model When the browser renders using the box model, each element is surrounded by: Padding The padding property determines the distance between the content inside an element and the edge of the element Padding be set for each side of the box by using padding-top, paddingright, padding-left and padding-bottom Margin Determines the distance between the element s edge and any outside text Margins for individual sides of an element can be specified by using margin-top, margin-right, margin-left and margin-bottom Border

152 Box Model and Text Flow (Cont.) The border is controlled using the properties: border-width May be set to any of the CSS lengths or to the predefined value of thin, medium or thick border-color Sets the color used for the border border-style Options are: none, hidden, dotted, dashed, solid, double, groove, ridge, inset and outset

153 Box Model and Text Flow (Cont.) class attribute allows more than one class to be assigned to an XHTML element by separating each class name from the next with a space

154 49 Fig Box model for block-level elements.

155 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 5.11: borders.html --> 6 <!-- Borders of block-level elements. --> 7 <html xmlns = " 8 <head> 9 <title>borders</title> 10 <style type = "text/css"> 11 div { text-align: center; 12 width: 50%; 13 position: relative; 14 left: 25%; 15 border-width: 4px } 16.medium { border-width: medium } 17.thin { border-width: thin } 18.solid { border-style: solid } 19.double { border-style: double } 20.groove { border-style: groove } 21.inset { border-style: inset } 22.outset { border-style: outset } 23.dashed { border-style: dashed } 24.red { border-color: red } 25.blue { border-color: blue } 26 </style> 27 </head> Fig Borders of block-level elements (Part 1 of 2). Defines several border classes Pearson Education, Inc. All rights reserved.

156 28 <body> 29 <div class = "solid">solid border</div><hr /> 30 <div class = "double">double border</div><hr /> 31 <div class = "groove">groove border</div><hr /> 32 <div class = "inset">inset border</div><hr /> 33 <div class = "dashed">dashed border</div><hr /> 34 <div class = "thin red solid">thin Red Solid border</div><hr /> 35 <div class = "medium blue outset">medium Blue Outset border</div> 36 </body> 37 </html> Applies several classes to the same element Fig Borders of block-level elements (Part 2 of 2) Pearson Education, Inc. All rights reserved.

157 Box Model and Text Flow (Cont.) Browsers normally place text and elements on screen in the order in which they appear in the XHTML file. Elements can be removed from the normal flow of text. Floating allows you to move an element to one side of the screen; other content in the document will then flow around the floated element

158 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 5.12: floating.html --> 6 <!-- Floating elements. --> 7 <html xmlns = " 8 <head> 9 <title>flowing Text Around Floating Elements</title> 10 <style type = "text/css"> 11 div.heading { background-color: #bbddff; 12 text-align: center; 13 font-family: arial, helvetica, sans-serif; 14 padding:.2em } 15 p { text-align: justify; 16 font-family: verdana, geneva, sans-serif; 17 margin:.5em } 18 div.floated { background-color: #eeeeee; 19 font-size: 1.5em; 20 font-family: arial, helvetica, sans-serif; 21 padding:.2em; 22 margin-left:.5em; 23 margin-bottom:.5em; 24 float: right; 25 text-align: right; 26 width: 50% } 27 div.section { border: 1px solid #bbddff } 28 </style> 29 </head> Defines the border for this div class Fig Floating elements (Part 1 of 3). Sets a spacing of.5 em from the outside of the border to all other content Sets a spacing of.2 em from the inside of the border to the element s content Define left and right margins Moves element to the right, and lets other content flow around it Pearson Education, Inc. All rights reserved.

159 30 <body> 31 <div class = "heading"><img src = "deitel.png" alt = "Deitel" /> 32 </div> 33 <div class = "section"> 34 <div class = "floated">corporate Training and Publishing</div> 35 <p>deitel & Associates, Inc. is an internationally 36 recognized corporate training and publishing organization 37 specializing in programming languages, Internet/World 38 Wide Web technology and object technology education. 39 The company provides courses on Java, C++, Visual Basic, C#, 40 C, Internet and web programming, Object 41 Technology, and more.</p> 42 </div> 43 <div class = "section"> 44 <div class = "floated">leading-edge Programming Textbooks</div> 45 <p>through its publishing 46 partnership with Prentice Hall, Deitel & Associates, 47 Inc. publishes leading-edge programming textbooks, 48 professional books, interactive CD-ROM-based multimedia 49 Cyber Classrooms, satellite courses and DVD and web-based 50 video courses.</p> 51 </div> 52 </body> 53 </html> Fig Floating elements (Part 2 of 3) Pearson Education, Inc. All rights reserved.

160 55 Fig Floating elements (Part 3 of 3).

161 Media Types CSS media types allow a programmer to decide what a page should look like depending on the kind of media being used to display the page Most common media type for a web page is the screen media type, which is a standard computer screen

162 Media Types (Cont.) A block of styles that applies to all media types is declared all and enclosed in curly braces To create a block of styles that apply to a single media type such as print, print and enclose the style rules in curly braces

163 Media Types (Cont.) Other media types in CSS 2 include: handheld Designed for mobile Internet devices braille For machines that can read or print web pages in braille aural Allow the programmer to give a speech-synthesizing web browser more information about the content of the web page print Affects a web page s appearance when it is printed

164 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 5.13: mediatypes.html --> 6 <!-- CSS media types. --> 7 <html xmlns = " 8 <head> 9 <title>media Types</title> 10 <style type = "text/css"> all 12 { 13 body { background-color: #4488aa } 14 h1 { font-family: verdana, helvetica, sans-serif; 15 color: #aaffcc } 16 p { font-size: 12pt; 17 color: white; 18 font-family: arial, sans-serif } 19 } /* all declaration. */ print 21 { 22 body { background-color: white } 23 h1 { color: #008844} 24 p { font-size: 14pt; 25 color: #4488aa; 26 font-family: "times new roman", times, serif } 27 } /* print declaration. */ 28 </style> 29 </head> 30 <body> 31 <h1>css Media Types Example</h1> Sets properties for all media types Fig CSS media types (Part 1 of 2). Sets properties for a page if it is being printed Pearson Education, Inc. All rights reserved.

165 32 33 <p> 34 This example uses CSS media types to vary how the page 35 appears in print and how it appears on any other media. 36 This text will appear one font on the screen and a 37 different font on paper or in a print preview. To see 38 the difference in Internet Explorer, go to the Print 39 menu and select Print Preview. In Firefox, select Print 40 Preview from the File menu. 41 </p> 42 </body> 43 </html> Fig CSS media types (Part 2 of 2) Pearson Education, Inc. All rights reserved.

166 Building a CSS Drop-Down Menu :hover pseudoclass used to apply styles to an element when the mouse cursor is over it display property allows a programmer to decide if an element is displayed as a block element, inline element, or is not rendered at all (none)

167 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 5.14: dropdown.html --> 6 <!-- CSS drop-down menu. --> 7 <html xmlns = " 8 <head> 9 <title> 10 Drop-Down Menu 11 </title> 12 <style type = "text/css"> 13 body { font-family: arial, sans-serif } 14 div.menu { font-weight: bold; 15 color: white; 16 border: 2px solid #225599; 17 text-align: center; 18 width: 10em; 19 background-color: # } 20 div.menu:hover a { display: block } 21 div.menu a { display: none; 22 border-top: 2px solid #225599; 23 background-color: white; 24 width: 10em; 25 text-decoration: none; 26 color: black } 27 div.menu a:hover { background-color: #dfeeff } 28 </style> 29 </head> 30 <body> Fig CSS dropdown menu (Part 1 of 2). Sets anchor elements in a menu div to be displayed as block-level when the menu is moused-over Prevents the browser from rendering the links inside the menu div Sets anchor elements in a menu div to have a lightblue background when they are moused-over Pearson Education, Inc. All rights reserved.

168 31 <div class = "menu">menu 32 <a href = "#">Home</a> 33 <a href = "#">News</a> 34 <a href = "#">Articles</a> 35 <a href = "#">Blog</a> 36 <a href = "#">Contact</a> 37 </div> 38 </body> 39 </html> Fig CSS dropdown menu (Part 2 of 2) Pearson Education, Inc. All rights reserved.

169 User Style Sheets Users can define their own user style sheets to format pages based on their preferences Absolute font size measurements override user style sheets, while relative font sizes will yield to a user-defined style User style sheets are not linked to a document; rather, they are set in the browser s options

170 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 5.15: user_absolute.html --> 6 <!-- pt measurement for text size. --> 7 <html xmlns = " 8 <head> 9 <title>user Styles</title> 10 <style type = "text/css"> 11.note { font-size: 9pt } 12 </style> 13 </head> 14 <body> 15 <p>thanks for visiting my website. I hope you enjoy it. 16 </p><p class = "note">please Note: This site will be 17 moving soon. Please check periodically for updates.</p> 18 </body> 19 </html> Fig pt measurement for text size. A class defined by the author with absolute measurements: a font-size of 9 pt Pearson Education, Inc. All rights reserved.

171 1 /* Fig. 5.16: userstyles.css */ 2 /* A user stylesheet */ 3 body { font-size: 20pt; 4 color: yellow; 5 background-color: # } A different font-size of 20 pt is defined by the user for all body elements Fig User style sheet Pearson Education, Inc. All rights reserved.

172 67 Fig User style sheet in Internet Explorer 7.

173 68 The author s style has higher precedence than the user s, so the font is 9 pt Fig User style sheet applied with pt measurement.

174 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 5.19: user_relative.html --> 6 <!-- em measurement for text size. --> 7 <html xmlns = " 8 <head> 9 <title>user Styles</title> 10 <style type = "text/css"> 11.note { font-size:.75em } 12 </style> 13 </head> 14 <body> 15 <p>thanks for visiting my website. I hope you enjoy it. 16 </p><p class = "note">please Note: This site will be 17 moving soon. Please check periodically for updates.</p> 18 </body> 19 </html> A relative measurement of.75 em is used by the author for the font size Fig em measurement for text size Pearson Education, Inc. All rights reserved.

175 The user style sheet is considered, so the font-size is 15 pt (.75 em for 20 pt) 70 Fig User style sheet applied with em measurement.

176 CSS 3 While CSS 2 is the current W3C Recommendation, CSS 3 is in development, and some browsers are beginning to implement some of the new features that will be in the CSS 3 specification CSS 3 will introduce new features related to borders, backgrounds, text effects, layout, and more

177 1 6 JavaScript: Introduction to Scripting

178 2 6.1 Introduction JavaScript Scripting language that facilitates a disciplined approach to designing computer programs that enhance the functionality and appearance of web pages. Before you can run code examples with JavaScript on your computer, you may need to change your browser s security settings. IE7 prevents scripts on the local computer from running by default FF2 enables JavaScript by default

179 3 Fig. 6.1 Enabling JavaScript in Internet Explorer 7

180 6.2 Simple Program: Displaying a Line of Text in a Web Page 4 Spacing displayed by a browser in a web page is determined by the XHTML elements used to format the page Often, JavaScripts appear in the <head> section of the XHTML document The browser interprets the contents of the <head> section first The <script> tag indicates to the browser that the text that follows is part of a script. Attribute type specifies the scripting language used in the script such as text/javascript

181 5 Portability Tip 6.1 Some browsers do not support the <script> </script> tags. If your document is to be rendered with such browsers, enclose the script code between these tags in an XHTML comment, so that the script text does not get displayed as part of the web page. The closing comment tag of the XHTML comment (-->) is preceded by a JavaScript comment (//) to prevent the browser from trying to interpret the XHTML comment as a JavaScript statement.

182 6.2 Simple Program: Displaying a Line of Text in a Web Page (Cont.) 6 A string of characters can be contained between double (") or single (') quotation marks A string is sometimes called a character string, a message or a string literal

183 6.2 Simple Program: Displaying a Line of Text in a Web Page (Cont.) 7 Browser s document object represents the XHTML document currently being displayed in the browser Allows a script programmer to specify XHTML text to be displayed in the XHTML document Browser contains a complete set of objects that allow script programmers to access and manipulate every element of an XHTML document Object Resides in the computer s memory and contains information used by the script The term object normally implies that attributes (data) and behaviors (methods) are associated with the object An object s methods use the attributes data to perform useful actions for the client of the object the script that calls the methods

184 6.2 Simple Program: Displaying a Line of Text in a Web Page (Cont.) 8 The parentheses following the name of a method contain the arguments that the method requires to perform its task (or its action) Every statement should end with a semicolon (also known as the statement terminator), although none is required by JavaScript JavaScript is case sensitive Not using the proper uppercase and lowercase letters is a syntax error

185 6.2 Simple Program: Displaying a Line of Text in a Web Page (Cont.) 9 The document object s writeln method Writes a line of XHTML text in the XHTML document Does not guarantee that a corresponding line of text will appear in the XHTML document. Text displayed is dependent on the contents of the string written, which is subsequently rendered by the browser. Browser will interpret the XHTML elements as it normally does to render the final text in the document

186 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 6.2: welcome.html --> 6 <!-- Displaying a line of text. --> 7 <html xmlns = " 8 <head> 9 <title>a First Program in JavaScript</title> 10 <script type = "text/javascript"> 11 <!-- 12 document.writeln( 13 "<h1>welcome to JavaScript Programming!</h1>" ); 14 // --> 15 </script> 16 </head><body></body> 17 </html> Script ends Script begins XHTML comment delimiter, commented for correct interpretation by all browsers Specifies that we are using the JavaScript language Writes an h1 welcome message in the XHTML document 10 Fig. 6.2 Displaying a line of text. Prevents older browsers that do not support scripting from displaying the text of the script 2008 Pearson Education, Inc. All rights reserved.

187 Modifying Our First Program Method write displays a string like writeln, but does not position the output cursor in the XHTML document at the beginning of the next line after writing its argument You cannot split a statement in the middle of a string. The + operator (called the concatenation operator when used in this manner) joins two strings together

188 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 6.3: welcome2.html --> 6 <!-- Printing one line with multiple statements. --> 7 <html xmlns = " 8 <head> 9 <title>printing a Line with Multiple Statements</title> 10 <script type = "text/javascript"> 11 <!-- 12 document.write( "<h1 style = \"color: magenta\">" ); 13 document.write( "Welcome to JavaScript " + 14 "Programming!</h1>" ); 15 // --> 16 </script> 17 </head><body></body> 18 </html> 12 Fig. 6.3 Printing one line with separate statements. Two write statements create one line of XHTML text Concatenation operator joins the string together, as it is split into multiple lines 2008 Pearson Education, Inc. All rights reserved.

189 6.3 Modifying Our First Program (Cont.) 13 A single statement can cause the browser to display multiple lines by using line-break XHTML tags ( <br/>) throughout the string of XHTML text in a write or writeln method call

190 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 6.4: welcome3.html --> 6 <!-- Printing on multiple lines with a single statement. --> 7 <html xmlns = " 8 <head> 9 <title>printing Multiple Lines</title> 10 <script type = "text/javascript"> 11 <!-- 12 document.writeln( "<h1>welcome to<br />JavaScript" + 13 "<br />Programming!</h1>" ); 14 // --> 15 </script> 16 </head><body></body> 17 </html> Inserts line-break Inserts line-break Fig. 6.4 Printing on multiple lines with a single statement Pearson Education, Inc. All rights reserved.

191 Modifying Our First Program (Cont.) Dialogs Useful to display information in windows that pop up on the screen to grab the user s attention Typically used to display important messages to the user browsing the web page Browser s window object uses method alert to display an alert dialog Method alert requires as its argument the string to be displayed

192 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 6.5: welcome4.html --> 6 <!-- Alert dialog displaying multiple lines. --> 7 <html xmlns = " 8 <head> 9 <title>printing Multiple Lines in a Dialog Box</title> 10 <script type = "text/javascript"> 11 <!-- 12 window.alert( "Welcome to\njavascript\nprogramming!" ); 13 // --> 14 </script> 15 </head> 16 <body> 17 <p>click Refresh (or Reload) to run this script again.</p> 18 </body> 19 </html> Creates a pop up box that alerts the welcome text to the user Fig. 6.5 Alert dialog displaying multiple lines Pearson Education, Inc. All rights reserved.

193 6.3 Modifying Our First Program (Cont.) 17 When a backslash is encountered in a string of characters, the next character is combined with the backslash to form an escape sequence. The escape sequence \n is the newline character. It causes the cursor in the XHTML document to move to the beginning of the next line.

194 Fig. 6.6 Some common escape sequences. 18 Escape sequence Description \n New line. Position the screen cursor at the beginning of the next line. \t Horizontal tab. Move the screen cursor to the next tab stop. \r Carriage return. Position the screen cursor to the beginning of the current line; do not advance to the next line. Any characters output after the carriage return overwrite the characters previously output on that line. \\ Backslash. Used to represent a backslash character in a string. \" Double quote. Used to represent a double-quote character in a string contained in double quotes. For example, \' window.alert( "\"in quotes\"" ); displays "in quotes" in an alert dialog. Single quote. Used to represent a single-quote character in a string. For example, window.alert( '\'in quotes\'' ); displays 'in quotes' in an alert dialog Pearson Education, Inc. All rights reserved.

195 6.4 Obtaining User Input with prompt Dialogs 19 Scripting Gives you the ability to generate part or all of a web page s content at the time it is shown to the user Such web pages are said to be dynamic, as opposed to static, since their content has the ability to change

196 6.4 Obtaining User Input with prompt Dialogs (Cont.) 20 Keywords are words with special meaning in JavaScript Keyword var Used to declare the names of variables A variable is a location in the computer s memory where a value can be stored for use by a program All variables have a name, type and value, and should be declared with a var statement before they are used in a program A variable name can be any valid identifier consisting of letters, digits, underscores ( _ ) and dollar signs ($) that does not begin with a digit and is not a reserved JavaScript keyword.

197 6.4 Obtaining User Input with prompt Dialogs (Cont.) 21 Declarations end with a semicolon (;) and can be split over several lines, with each variable in the declaration separated by a comma (forming a comma-separated list of variable names) Several variables may be declared in one declaration or in multiple declarations. Comments A single-line comment begins with the characters // and terminates at the end of the line Comments do not cause the browser to perform any action when the script is interpreted; rather, comments are ignored by the JavaScript interpreter Multiline comments begin with delimiter /* and end with delimiter */ All text between the delimiters of the comment is ignored by the interpreter.

198 6.4 Obtaining User Input with prompt Dialogs (Cont.) 22 The window object s prompt method displays a dialog into which the user can type a value. The first argument is a message (called a prompt) that directs the user to take a specific action. The optional second argument is the default string to display in the text field. Script can then use the value that the user inputs. A variable is assigned a value with an assignment statement, using the assignment operator, =. The = operator is called a binary operator, because it has two operands.

199 6.4 Obtaining User Input with prompt Dialogs (Cont.) 23 null keyword Signifies that a variable has no value null is not a string literal, but rather a predefined term indicating the absence of value Writing a null value to the document, however, displays the word null Function parseint converts its string argument to an integer JavaScript has a version of the + operator for string concatenation that enables a string and a value of another data type (including another string) to be concatenated

200 24 Common Programming Error 6.10 Confusing the + operator used for string concatenation with the + operator used for addition often leads to undesired results. For example, if integer variable y has the value 5, the expression "y + 2 = " + y + 2 results in "y + 2 = 52", not "y + 2 = 7", because first the value of y (i.e., 5) is concatenated with the string "y + 2 = ", then the value 2 is concatenated with the new, larger string "y + 2 = 5". The expression "y + 2 = " + (y + 2) produces the string "y + 2 = 7" because the parentheses ensure that y + 2 is executed mathematically before it is converted to a string.

201 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 6.7: welcome5.html --> 6 <!-- Prompt box used on a welcome screen. --> 7 <html xmlns = " 8 <head> 9 <title>using Prompt and Alert Boxes</title> 10 <script type = "text/javascript"> 11 <!-- 12 var name; // string entered by the user // read the name from the prompt box as a string 15 name = window.prompt( "Please enter your name" ); document.writeln( "<h1>hello, " + name + 18 ", welcome to JavaScript programming!</h1>" ); 19 // --> 20 </script> 21 </head> 22 <body> 23 <p>click Refresh (or Reload) to run this script again.</p> 24 </body> 25 </html> Declares a new variable Sets the identifier of the variable to name Assigns the string entered by the user to the variable name 25 Fig. 6.7 Prompt box used on a welcome screen (Part 1 of 2). Inserts the value given to name into the XHTML text 2008 Pearson Education, Inc. All rights reserved.

202 26 Fig. 6.7 Prompt box used on a welcome screen (Part 2 of 2).

203 27 Fig. 6.8 Prompt dialog displayed by the window object s prompt method.

204 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 6.9: addition.html --> 6 <!-- Addition script. --> 7 <html xmlns = " 8 <head> 9 <title>an Addition Program</title> 10 <script type = "text/javascript"> 11 <!-- 12 var firstnumber; // first string entered by user 13 var secondnumber; // second string entered by user 14 var number1; // first number to add 15 var number2; // second number to add 16 var sum; // sum of number1 and number // read in first number from user as a string 19 firstnumber = window.prompt( "Enter first integer" ); // read in second number from user as a string 22 secondnumber = window.prompt( "Enter second integer" ); // convert numbers from strings to integers 25 number1 = parseint( firstnumber ); 26 number2 = parseint( secondnumber ); sum = number1 + number2; // add the numbers 29 Fig. 6.9 Addition script (Part 1 of 2). Assigns the first input from the user to the variable firstnumber Assigns the second input from the user to the variable secondnumber Converts the strings entered by the user into integers Pearson Education, Inc. All rights reserved.

205 30 // display the results 31 document.writeln( "<h1>the sum is " + sum + "</h1>" ); 32 // --> 33 </script> 34 </head> 35 <body> 36 <p>click Refresh (or Reload) to run the script again</p> 37 </body> 38 </html> Fig. 6.9 Addition script (Part 2 of 2) Pearson Education, Inc. All rights reserved.

206 Memory Concepts Variable names correspond to locations in the computer s memory. Every variable has a name, a type and a value. When a value is placed in a memory location, the value replaces the previous value in that location. When a value is read out of a memory location, the process is nondestructive.

207 31 Fig Memory location showing the name and value of variable number1.

208 32 Fig Memory locations after inputting values for variables number1 and number2.

209 33 Fig Memory locations after calculating the sum of number1 and number2.

210 Memory Concepts (Cont.) JavaScript does not require variables to have a type before they can be used in a program A variable in JavaScript can contain a value of any data type, and in many situations, JavaScript automatically converts between values of different types for you JavaScript is referred to as a loosely typed language When a variable is declared in JavaScript, but is not given a value, it has an undefined value. Attempting to use the value of such a variable is normally a logic error. When variables are declared, they are not assigned default values, unless specified otherwise by the programmer. To indicate that a variable does not contain a value, you can assign the value null to it.

211 Arithmetic The basic arithmetic operators (+, -, *, /, and %) are binary operators, because they each operate on two operands JavaScript provides the remainder operator, %, which yields the remainder after division Arithmetic expressions in JavaScript must be written in straight-line form to facilitate entering programs into the computer

212 Fig Arithmetic operators. 36 JavaScript operation Arithmetic operator Algebraic expression JavaScript expression Addition + f + 7 F + 7 Subtraction - p c P - c Multiplication * bm b * m Division / x / y or x y or x y x / y Remainder % r mod s r % s Fig Precedence of arithmetic operators. Operator(s) Operation(s) Order of evaluation (precedence) *, / or % Multiplication Division Remainder + or - Addition Subtraction Evaluated first. If there are several such operations, they are evaluated from left to right. Evaluated last. If there are several such operations, they are evaluated from left to right Pearson Education, Inc. All rights reserved.

213 Arithmetic (Cont.) Parentheses can be used to group expressions as in algebra. Operators in arithmetic expressions are applied in a precise sequence determined by the rules of operator precedence: Multiplication, division and remainder operations are applied first. If an expression contains several of these operations, operators are applied from left to right. Multiplication, division and remainder operations are said to have the same level of precedence. Addition and subtraction operations are applied next. If an expression contains several of these operations, operators are applied from left to right. Addition and subtraction operations have the same level of precedence. When we say that operators are applied from left to right, we are referring to the associativity of the operators. Some operators associate from right to left.

214 38 Fig Order in which a second-degree polynomial is evaluated.

215 6.7 Decision Making: Equality and Relational Operators 39 if statement allows a program to make a decision based on the truth or falsity of a condition If the condition is met (i.e., the condition is true), the statement in the body of the if statement is executed If the condition is not met (i.e., the condition is false), the statement in the body of the if statement is not executed Conditions in if statements can be formed by using the equality operators and relational operators

216 40 Fig Equality and relational operators. Standard algebraic equality operator or relational operator Equality operators JavaScript equality or relational operator Sample JavaScript condition Meaning of JavaScript condition = == x == y x is equal to y!= x!= y x is not equal to y Relational operators > > x > y x is greater than y < < x < y x is less than y >= x >= y x is greater than or equal to y < <= x <= y x is less than or equal to y

217 6.7 Decision Making: Equality and Relational Operators (Cont.) 41 Equality operators both have the same level of precedence, which is lower than the precedence of the relational operators. The equality operators associate from left to right. If more than one variable is declared in a single declaration, the names are separated by commas (,) This list of names is referred to as a comma-separated list

218 6.7 Decision Making: Equality and Relational Operators (Cont.) 42 Date object Used acquire the current local time Create a new instance of an object by using the new operator followed by the type of the object, Date, and a pair of parentheses

219 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 6.17: welcome6.html --> 6 <!-- Using equality and relational operators. --> 7 <html xmlns = " 8 <head> 9 <title>using Relational Operators</title> 10 <script type = "text/javascript"> 11 <!-- 12 var name; // string entered by the user 13 var now = new Date(); // current date and time 14 var hour = now.gethours(); // current hour (0-23) // read the name from the prompt box as a string 17 name = window.prompt( "Please enter your name" ); // determine whether it is morning 20 if ( hour < 12 ) 21 document.write( "<h1>good Morning, " ); 22 Set variable now to a new Date object Assigns hour to the value returned by the Date object s gethours method Conditional statement: checks whether the current value of hour is less than 12 This statement will execute only if the previous condition was true Fig Using equality and relational operators (Part 1 of 3) Pearson Education, Inc. All rights reserved.

220 23 // determine whether the time is PM 24 if ( hour >= 12 ) 25 { 26 // convert to a 12-hour clock 27 hour = hour - 12; // determine whether it is before 6 PM 30 if ( hour < 6 ) 31 document.write( "<h1>good Afternoon, " ); // determine whether it is after 6 PM 34 if ( hour >= 6 ) 35 document.write( "<h1>good Evening, " ); 36 } // end if document.writeln( name + 39 ", welcome to JavaScript programming!</h1>" ); 40 // --> 41 </script> 42 </head> 43 <body> 44 <p>click Refresh (or Reload) to run this script again.</p> 45 </body> 46 </html> Conditional statement: checks whether the current value of hour is greater than or equal to 12 If hour is 12 or greater (the previous condition was true), subtract 12 from the value and reassign it to hour Conditional statement: checks whether the current value of hour is less than 6 Conditional statement: checks whether the current value of hour is greater than or equal to 6 44 Fig Using equality and relational operators (Part 2 of 3) Pearson Education, Inc. All rights reserved.

221 45 Fig Using equality and relational operators (Part 3 of 3).

222 46 Fig Precedence and associativity of the operators discussed so far. Operators Associativity Type * / % left to right multiplicative + - left to right additive < <= > >= left to right relational ==!= left to right equality = right to left assignment 2008 Pearson Education, Inc. All rights reserved.

223 1 7 JavaScript: Control Statements I

224 2 7.1 Introduction The techniques you will learn here are applicable to most high-level languages, including JavaScript

225 3 7.2 Algorithms Any computable problem can be solved by executing a series of actions in a specific order A procedure for solving a problem in terms of the actions to execute and the order in which the actions are to execute is called an algorithm Specifying the order in which statements are to be executed in a computer program is called program control

226 4 7.3 Pseudocode Pseudocode An artificial and informal language that helps programmers develop algorithms Carefully prepared pseudocode may be converted easily to a corresponding JavaScript program Normally describes only executable statements the actions that are performed when the program is converted from pseudocode to JavaScript and executed

227 5 7.4 Control Structures Sequential execution Execute statements in the order they appear in the code Transfer of control Changing the order in which statements execute All programs can be written in terms of only three control structures sequence selection repetition

228 6 7.4 Control Structures (Cont.) Flowchart A graphical representation of an algorithm or of a portion of an algorithm Drawn using certain special-purpose symbols, such as rectangles, diamonds, ovals and small circles Symbols are connected by arrows called flowlines, which indicate the order in which the actions of the algorithm execute

229 7 7.4 Control Structures (Cont.) In a flowchart that represents a complete algorithm, an oval symbol containing the word Begin is the first symbol used; an oval symbol containing the word End indicates where the algorithm ends. In a flowchart that shows only a portion of an algorithm, the oval symbols are omitted in favor of using small circle symbols, also called connector symbols. Perhaps the most important flowcharting symbol is the diamond symbol, also called the decision symbol, which indicates that a decision is to be made.

230 8 Indicates a portion of an algorithm Fig. 7.1 Flowcharting JavaScript s sequence structure.

231 9 7.4 Control Structures (Cont.) JavaScript provides three selection structures. The if statement either performs (selects) an action if a condition is true or skips the action if the condition is false. Called a single-selection structure because it selects or ignores a single action or group of actions. The if else statement performs an action if a condition is true and performs a different action if the condition is false. Double-selection structure because it selects between two different actions or group of actions. The switch statement performs one of many different actions, depending on the value of an expression. Multiple-selection structure because it selects among many different actions or groups of actions.

232 Control Structures (Cont.) JavaScript provides four repetition statements, namely, while, do while, for and for in. Keywords cannot be used as identifiers (e.g., for variable names).

233 Fig. 7.2 JavaScript keywords. 11 JavaScript keywords break case catch continue default delete do else false finally for function if in instanceof new null return switch this throw true try typeof var void while with Keywords that are reserved but not used by JavaScript abstract boolean byte char class const debugger double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile 2008 Pearson Education, Inc. All rights reserved.

234 Control Structures (Cont.) Single-entry/single-exit control structures make it easy to build programs. Control structures are attached to one another by connecting the exit point of one control structure to the entry point of the next. Control-structure stacking. There is only one other way control structures may be connected Control-structure nesting

235 if Selection Statement The JavaScript interpreter ignores white-space characters blanks, tabs and newlines used for indentation and vertical spacing Programmers insert white-space characters to enhance program clarity A decision can be made on any expression that evaluates to a value of JavaScript s boolean type (i.e., any expression that evaluates to true or false). The indentation convention you choose should be carefully applied throughout your programs It is difficult to read programs that do not use uniform spacing conventions

236 14 If grade >= 60, execute this statement Otherwise Fig. 7.3 Flowcharting the single-selection if statement.

237 if...else Selection Statement Allows the programmer to specify that different actions should be performed when the condition is true and when the condition is false.

238 7.6 if...else Selection Statement (Cont.) 16 Conditional operator (?:) Closely related to the if else statement JavaScript s only ternary operator it takes three operands The operands together with the?: operator form a conditional expression The first operand is a boolean expression The second is the value for the conditional expression if the boolean expression evaluates to true Third is the value for the conditional expression if the boolean expression evaluates to false

239 17 Otherwise If the condition is met This is executed This is executed Fig. 7.4 Flowcharting the double-selection if else statement.

240 7.6 if...else Selection Statement (Cont.) 18 Nested if else statements Test for multiple cases by placing if else statements inside other if else structures The JavaScript interpreter always associates an else with the previous if, unless told to do otherwise by the placement of braces ({}) The if selection statement expects only one statement in its body To include several statements, enclose the statements in braces ({ and }) A set of statements contained within a pair of braces is called a block

241 7.6 if...else Selection Statement (Cont.) 19 A logic error has its effect at execution time. A fatal logic error causes a program to fail and terminate prematurely. A nonfatal logic error allows a program to continue executing, but the program produces incorrect results.

242 while Repetition Statement while Allows the programmer to specify that an action is to be repeated while some condition remains true The body of a loop may be a single statement or a block Eventually, the condition becomes false and repetition terminates

243 21 And evaluate if this statement is still true Break out of the cycle when the statement is false If this statement is true Execute this statement Fig. 7.5 Flowcharting the while repetition statement.

244 7.8 Formulating Algorithms: Counter- Controlled Repetition 22 Counter-controlled repetition Often called definite repetition, because the number of repetitions is known before the loop begins executing A total is a variable in which a script accumulates the sum of a series of values Variables that store totals should normally be initialized to zero before they are used in a program A counter is a variable a script uses to count typically in a repetition statement

245 7.8 Formulating Algorithms: Counter- Controlled Repetition 23 Uninitialized variables used in mathematical calculations result in logic errors and produce the value NaN (not a number) JavaScript represents all numbers as floatingpoint numbers in memory Floating-point numbers often develop through division The computer allocates only a fixed amount of space to hold such a value, so the stored floatingpoint value can only be an approximation

246 24 Set total to zero Set grade counter to one While grade counter is less than or equal to ten Input the next grade Add the grade into the total Add one to the grade counter Set the class average to the total divided by ten Print the class average Fig. 7.6 Pseudocode algorithm that uses counter-controlled repetition to solve the class-average problem.

247 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 7.7: average.html --> 6 <!-- Counter-controlled repetition to calculate a class average. --> 7 <html xmlns = " 8 <head> 9 <title>class Average Program</title> 10 <script type = "text/javascript"> 11 <!-- 12 var total; // sum of grades 13 var gradecounter; // number of grades entered 14 var grade; // grade typed by user (as a string) 15 var gradevalue; // grade value (converted to integer) 16 var average; // average of all grades // Initialization Phase 19 total = 0; // clear total 20 gradecounter = 1; // prepare to loop // Processing Phase 23 while ( gradecounter <= 10 ) // loop 10 times 24 { // prompt for input and read grade from user 27 grade = window.prompt( "Enter integer grade:", "0" ); 28 Stores the sum of grades Sets total to 0 Sets gradecounter to 1 in preparation for the loop 25 Fig. 7.7 Countercontrolled repetition to calculate a class average (Part 1 of 3). Continues the cycle until gradecounter is greater than Pearson Education, Inc. All rights reserved.

248 29 // convert grade from a string to an integer 30 gradevalue = parseint( grade ); // add gradevalue to total 33 total = total + gradevalue; // add 1 to gradecounter 36 gradecounter = gradecounter + 1; 37 } // end while // Termination Phase 40 average = total / 10; // calculate the average // display average of exam grades 43 document.writeln( 44 "<h1>class average is " + average + "</h1>" ); 45 // --> 46 </script> 47 </head> 48 <body> 49 <p>click Refresh (or Reload) to run the script again<p> 50 </body> 51 </html> Increments gradecounter by 1 after each iteration of the loop 26 Fig. 7.7 Countercontrolled repetition to calculate a class average (Part 2 of 3) Pearson Education, Inc. All rights reserved.

249 27 Fig. 7.7 Counter-controlled repetition to calculate a class average (Part 3 of 3).

250 7.9 Formulating Algorithms: Sentinel- Controlled Repetition 28 Sentinel-controlled repetition Special value called a sentinel value (also called a signal value, a dummy value or a flag value) indicates the end of data entry Often is called indefinite repetition, because the number of repetitions is not known in advance Choose a sentinel value that cannot be confused with an acceptable input value

251 7.9 Formulating Algorithms: Sentinel- Controlled Repetition (Cont.) 29 Top-down, stepwise refinement A technique that is essential to the development of wellstructured algorithms Approach begins with pseudocode of the top, the statement that conveys the program s overall purpose Divide the top into a series of smaller tasks and list them in the order in which they need to be performed the first refinement Second refinement commits to specific variables

252 Initialize total to zero Initialize gradecounter to zero 30 Input the first grade (possibly the sentinel) While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel) If the counter is not equal to zero Set the average to the total divided by the counter Print the average Else Print No grades were entered Fig. 7.8 Sentinel-controlled repetition to solve the class-average problem.

253 7.9 Formulating Algorithms: Sentinel- Controlled Repetition (Cont.) 31 Control structures may be stacked on top of one another in sequence

254 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 7.9: average2.html --> 6 <!-- Sentinel-controlled repetition to calculate a class average. --> 7 <html xmlns = " 8 <head> 9 <title>class Average Program: Sentinel-controlled Repetition</title> <script type = "text/javascript"> 12 <!-- 13 var total; // sum of grades 14 var gradecounter; // number of grades entered 15 var grade; // grade typed by user (as a string) 16 var gradevalue; // grade value (converted to integer) 17 var average; // average of all grades // Initialization phase 20 total = 0; // clear total 21 gradecounter = 0; // prepare to loop // Processing phase 24 // prompt for input and read grade from user 25 grade = window.prompt( 26 "Enter Integer Grade, -1 to Quit:", "0" ); // convert grade from a string to an integer 29 gradevalue = parseint( grade ); 30 Set gradecounter to 0 in preparation for the loop 32 Fig. 7.9 Sentinelcontrolled repetition to calculate a class average (Part 1 of 3) Pearson Education, Inc. All rights reserved.

255 31 while ( gradevalue!= -1 ) 32 { 33 // add gradevalue to total 34 total = total + gradevalue; // add 1 to gradecounter 37 gradecounter = gradecounter + 1; // prompt for input and read grade from user 40 grade = window.prompt( 41 "Enter Integer Grade, -1 to Quit:", "0" ); // convert grade from a string to an integer 44 gradevalue = parseint( grade ); 45 } // end while // Termination phase 48 if ( gradecounter!= 0 ) 49 { 50 average = total / gradecounter; // display average of exam grades 53 document.writeln( 54 "<h1>class average is " + average + "</h1>" ); 55 } // end if 56 else 57 document.writeln( "<p>no grades were entered</p>" ); 58 // --> 59 </script> 60 </head> 61 <body> Executes until gradevalue equals <p>click Refresh (or Reload) to run the script again</p> Increments gradecounter by 1 after each iteration of the loop Begin new control structure Execute if the condition in the if statement is not satisfied 33 Fig. 7.9 Sentinelcontrolled repetition to calculate a class average (Part 2 of 3) Pearson Education, Inc. All rights reserved.

256 34 Fig. 7.9 Sentinel-controlled repetition to calculate a class average (Part 3 of 3).

257 Initialize passes to zero Initialize failures to zero Initialize student to one While student counter is less than or equal to ten Input the next exam result If the student passed Add one to passes Else Add one to failures Add one to student counter Print the number of passes Print the number of failures If more than eight students passed Print Raise tuition 35 Fig Examination-results problem pseudocode.

258 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 7.11: analysis.html --> 6 <!-- Examination-results calculation. --> 7 <html xmlns = " 8 <head> 9 <title>analysis of Examination Results</title> 10 <script type = "text/javascript"> 11 <!-- 12 // initializing variables in declarations 13 var passes = 0; // number of passes 14 var failures = 0; // number of failures 15 var student = 1; // student counter 16 var result; // one exam result // process 10 students; counter-controlled loop 19 while ( student <= 10 ) 20 { 21 result = window.prompt( "Enter result (1=pass,2=fail)", "0" ); if ( result == "1" ) 24 passes = passes + 1; 25 else 26 failures = failures + 1; student = student + 1; 29 } // end while 30 Outer control structure Start nested control structure End nested control structure Increment for while loop 36 Fig Examinationresults calculation (Part 1 of 3) Pearson Education, Inc. All rights reserved.

259 31 // termination phase 32 document.writeln( "<h1>examination Results</h1>" ); 33 document.writeln( 34 "Passed: " + passes + "<br />Failed: " + failures ); if ( passes > 8 ) Additional control structure 37 document.writeln( "<br />Raise Tuition" ); 38 // --> 39 </script> 40 </head> 41 <body> 42 <p>click Refresh (or Reload) to run the script again</p> 43 </body> 44 </html> 37 Fig Examinationresults calculation (Part 2 of 3) Pearson Education, Inc. All rights reserved.

260 38 Fig Examination-results calculation (Part 3 of 3).

261 Assignment Operators JavaScript provides the arithmetic assignment operators +=, -=, *=, /= and %=, which abbreviate certain common types of expressions.

262 Fig Arithmetic assignment operators. 40 Assignment operator Initial value of variable Sample expression Explanation Assigns += c = 3 c += 7 c = c to c -= d = 5 d -= 4 d = d to d *= e = 4 e *= 5 e = e * 5 20 to e /= f = 6 f /= 3 f = f / 3 2 to f %= g = 12 g %= 9 g = g % 9 3 to g 2008 Pearson Education, Inc. All rights reserved.

263 7.12 Increment and Decrement Operators 41 The increment operator, ++, and the decrement operator, --, increment or decrement a variable by 1, respectively. If the operator is prefixed to the variable, the variable is incremented or decremented by 1, then used in its expression. If the operator is postfixed to the variable, the variable is used in its expression, then incremented or decremented by 1.

264 Fig Increment and decrement operators. 42 Operator Example Called Explanation ++ ++a preincrement Increment a by 1, then use the new value of a in the expression in which a resides. ++ a++ postincrement Use the current value of a in the expression in which a resides, then increment a by b predecrement Decrement b by 1, then use the new value of b in the expression in which b resides. -- b-- postdecrement Use the current value of b in the expression in which b resides, then decrement b by Pearson Education, Inc. All rights reserved.

265 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 7.14: increment.html --> 6 <!-- Preincrementing and Postincrementing. --> 7 <html xmlns = " 8 <head> 9 <title>preincrementing and Postincrementing</title> 10 <script type = "text/javascript"> 11 <!-- 12 var c; c = 5; 15 document.writeln( "<h3>postincrementing</h3>" ); 16 document.writeln( c ); // prints 5 17 // prints 5 then increments 18 document.writeln( "<br />" + c++ ); 19 document.writeln( "<br />" + c ); // prints c = 5; 22 document.writeln( "<h3>preincrementing</h3>" ); 23 document.writeln( c ); // prints 5 24 // increments then prints 6 25 document.writeln( "<br />" + ++c ); 26 document.writeln( "<br />" + c ); // prints 6 27 // --> 28 </script> 29 </head><body></body> 30 </html> Fig Preincrementing and postincrementing (Part 1 of 2). Prints value of c, then increments it Increments c, then prints its value Pearson Education, Inc. All rights reserved.

266 44 Fig Preincrementing and postincrementing (Part 2 of 2).

267 7.12 Increment and Decrement Operators (Cont.) 45 When incrementing or decrementing a variable in a statement by itself, the preincrement and postincrement forms have the same effect, and the predecrement and postdecrement forms have the same effect When a variable appears in the context of a larger expression, preincrementing the variable and postincrementing the variable have different effects. Predecrementing and postdecrementing behave similarly.

268 Fig Precedence and associativity of the operators discussed so far. 46 Operator Associativity Type right to left unary * / % left to right multiplicative + - left to right additive < <= > >= left to right relational ==!= left to right equality?: right to left conditional = += -= *= /= %= right to left assignment 2008 Pearson Education, Inc. All rights reserved.

269 1 8 JavaScript: Control Statements II

270 2 8.1 Introduction The techniques you will learn here are applicable to most high-level languages, including JavaScript.

271 8.2 Essentials of Counter-Controlled Repetition 3 Counter-controlled repetition requires name of a control variable initial value of the control variable the increment (or decrement) by which the control variable is modified each time through the loop the condition that tests for the final value of the control variable to determine whether looping should continue

272 8.2 Essentials of Counter-Controlled Repetition (Cont.) 4 The double-quote character delimits the beginning and end of a string literal in JavaScript it cannot be used in a string unless it is preceded by a \ to create the escape sequence \ XHTML allows either single quotes (') or double quotes (") to be placed around the value specified for an attribute JavaScript allows single quotes to be placed in a string literal

273 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 8.1: WhileCounter.html --> 6 <!-- Counter-controlled repetition. --> 7 <html xmlns = " 8 <head> 9 <title>counter-controlled Repetition</title> 10 <script type = "text/javascript"> 11 <!-- 12 var counter = 1; // initialization while ( counter <= 7 ) // repetition condition 15 { 16 document.writeln( "<p style = \"font-size: " + 17 counter + "ex\">xhtml font size " + counter + 18 "ex</p>" ); 19 ++counter; // increment 20 } //end while 21 // --> 22 </script> 23 </head><body></body> 24 </html> Incrementing statement Initializes counter Condition to be fulfilled with every iteration Fig. 8.1 Countercontrolled repetition (Part 1 of 2). Precedes the with a \ to create an escape sequence so that it can be used in the string Pearson Education, Inc. All rights reserved.

274 6 Fig. 8.1 Counter-controlled repetition (Part 2 of 2).

275 7 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable Can use a block to put multiple statements into the body If the loop s condition uses a < or > instead of a <= or >=, or viceversa, it can result in an off-by-one error for statement takes three expressions Initialization Condition Increment Expression The increment expression in the for statement acts like a stand-alone statement at the end of the body of the for statement Place only expressions involving the control variable in the initialization and increment sections of a for statement

276 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 8.2: ForCounter.html --> 6 <!-- Counter-controlled repetition with the for statement. --> 7 <html xmlns = " 8 <head> 9 <title>counter-controlled Repetition</title> 10 <script type = "text/javascript"> 11 <!-- 12 // Initialization, repetition condition and 13 // incrementing are all included in the for 14 // statement header. 15 for ( var counter = 1; counter <= 7; ++counter ) 16 document.writeln( "<p style = \"font-size: " + 17 counter + "ex\">xhtml font size " + counter + 18 "ex</p>" ); 19 // --> 20 </script> 21 </head><body></body> 22 </html> Initial value of the control variable Condition to test whether looping should continue Statement inside the for loop Fig. 8.2 Countercontrolled repetition with the for statement (Part 1 of 2). Increment to occur after each iteration of the loop Pearson Education, Inc. All rights reserved.

277 9 Fig. 8.2 Counter-controlled repetition with the for statement (Part 2 of 2).

278 for Repetition Statement (Cont.) The three expressions in the for statement are optional The two semicolons in the for statement are required The initialization, loop-continuation condition and increment portions of a for statement can contain arithmetic expressions

279 for Repetition Statement (Cont.) The part of a script in which a variable name can be used is known as the variable s scope The increment of a for statement may be negative, in which case it is called a decrement and the loop actually counts downward If the loop-continuation condition initially is false, the body of the for statement is not performed Execution proceeds with the statement following the for statement

280 12 Fig. 8.3 for statement header components.

281 13 Fig. 8.4 for repetition statement flowchart.

282 Examples Using the for Statement JavaScript does not include an exponentiation operator Math object s pow method for this purpose. Math.pow(x, y) calculates the value of x raised to the yth power. Floating-point numbers can cause trouble as a result of rounding errors

283 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 8.5: Sum.html --> 6 <!-- Summation with the for repetition structure. --> 7 <html xmlns = " 8 <head> 9 <title>sum the Even Integers from 2 to 100</title> 10 <script type = "text/javascript"> 11 <!-- 12 var sum = 0; for ( var number = 2; number <= 100; number += 2 ) 15 sum += number; document.writeln( "The sum of the even integers " + 18 "from 2 to 100 is " + sum ); 19 // --> 20 </script> 21 </head><body></body> 22 </html> 15 Fig. 8.5 Summation with the for repetition structure. After each loop iteration is complete, increment number by 2 We execute the loop while number is less than or equal to 100 Control variable number begins at the value of Pearson Education, Inc. All rights reserved.

284 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 8.6: Interest.html --> 6 <!-- Compound interest calculation with a for loop. --> 7 <html xmlns = " 8 <head> 9 <title>calculating Compound Interest</title> 10 <style type = "text/css"> 11 table { width: 100% } 12 th { text-align: left } 13 </style> 14 <script type = "text/javascript"> 15 <!-- 16 var amount; // current amount of money 17 var principal = ; // principal amount 18 var rate =.05; // interest rate document.writeln( 21 "<table border = \"1\">" ); // begin the table 22 document.writeln( 23 "<caption>calculating Compound Interest</caption>" ); 24 document.writeln( 25 "<thead><tr><th>year</th>" ); // year column heading 26 document.writeln( 27 "<th>amount on deposit</th>" ); // amount column heading 28 document.writeln( "</tr></thead><tbody>" ); Fig. 8.6 Compound interest calculation with a for loop (Part 1 of 2) Pearson Education, Inc. All rights reserved.

285 30 // output a table row for each year 31 for ( var year = 1; year <= 10; ++year ) 32 { 33 amount = principal * Math.pow( rate, year ); 34 document.writeln( "<tr><td>" + year + 35 "</td><td>" + amount.tofixed(2) + 36 "</td></tr>" ); 37 } //end for document.writeln( "</tbody></table>" ); 40 // --> 41 </script> 42 </head><body></body> 43 </html> Control variable year begins with a value of 1 Continue to execute the loop while year is less than or equal to 10 After each loop iteration, increase the value of year by 1 17 Fig. 8.6 Compound interest calculation with a for loop (Part 2 of 2) Pearson Education, Inc. All rights reserved.

286 switch Multiple-Selection Statement switch multiple-selection statement Tests a variable or expression separately for each of the values it may assume Different actions are taken for each value CSS property list-style-type Allows you to set the numbering system for a list Possible values include decimal (numbers the default) lower-roman (lowercase roman numerals) upper-roman (uppercase roman numerals) lower-alpha (lowercase letters) upper-alpha (uppercase letters) others

287 8.5 switch Multiple-Selection Statement (Cont.) 19 switch statement Consists of a series of case labels and an optional default case When control reaches a switch statement The script evaluates the controlling expression in the parentheses Compares this value with the value in each of the case labels If the comparison evaluates to true, the statements after the case label are executed in order until a break statement is reached The break statement is used as the last statement in each case to exit the switch statement immediately The default case allows you to specify a set of statements to execute if no other case is satisfied Usually the last case in the switch statement

288 8.5 switch Multiple-Selection Statement (Cont.) 20 Each case can have multiple actions (statements) Braces are not required around multiple actions in a case of a switch The break statement is not required for the last case because program control automatically continues with the next statement after the switch Having several case labels listed together (e.g., case 1: case 2: with no statements between the cases) executes the same set of actions for each case

289 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 8.7: SwitchTest.html --> 6 <!-- Using the switch multiple-selection statement. --> 7 <html xmlns = " 8 <head> 9 <title>switching between XHTML List Formats</title> 10 <script type = "text/javascript"> 11 <!-- 12 var choice; // user s choice 13 var starttag; // starting list item tag 14 var endtag; // ending list item tag 15 var validinput = true; // indicates if input is valid 16 var listtype; // type of list as a string choice = window.prompt( "Select a list style:\n" + 19 "1 (numbered), 2 (lettered), 3 (roman)", "1" ); switch ( choice ) 22 { 23 case "1": 24 starttag = "<ol>"; 25 endtag = "</ol>"; 26 listtype = "<h1>numbered List</h1>"; 27 break; 28 case "2": 29 starttag = "<ol style = \"list-style-type: upper-alpha\">"; 30 endtag = "</ol>"; Statements Statements 31 listtype = "<h1>lettered List</h1>"; Beginning of switch statement Beginning of statements to be executed if choice equals 1 Break out of switch statement 21 Fig. 8.7 Using the switch multipleselection statement (Part 1 of 4). Beginning of statements to be executed if choice equals 2 Break out of switch statement 2008 Pearson Education, Inc. All rights reserved.

290 33 case "3": 34 starttag = "<ol style = \"list-style-type: upper-roman\">"; 35 endtag = "</ol>"; 36 listtype = "<h1>roman Numbered List</h1>"; 37 break; 38 default: 39 validinput = false; 40 } //end switch if ( validinput == true ) 43 { 44 document.writeln( listtype + starttag ); for ( var i = 1; i <= 3; ++i ) 47 document.writeln( "<li>list item " + i + "</li>" ); document.writeln( endtag ); 50 } //end if 51 else 52 document.writeln( "Invalid choice: " + choice ); 53 // --> 54 </script> 55 </head> 56 <body> 57 <p>click Refresh (or Reload) to run the script again</p> 58 </body> 59 </html> Beginning of statements to be executed if choice equals 3 Break out of switch statement Beginning of statements to be executed if choice is anything other than 1, 2 or 3 No break is necessary, since we ve come to the end of the switch anyway Fig. 8.7 Using the switch multipleselection statement (Part 2 of 4) Pearson Education, Inc. All rights reserved.

291 23 Fig. 8.7 Using the switch multiple-selection statement (Part 3 of 4).

292 24 Fig. 8.7 Using the switch multiple-selection statement (Part 4 of 4).

293 If the controlling expression is equal to the case label 25 If none of the case labels are matched, execute the default actions Execute the following statements Until a break (or the end of the switch) is reached Fig. 8.8 switch multiple-selection statement.

294 do while Repetition Statement do while statement tests the loop-continuation condition after the loop body executes The loop body always executes at least once

295 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 8.9: DoWhileTest.html --> 6 <!-- Using the do...while repetition statement. --> 7 <html xmlns = " 8 <head> 9 <title>using the do...while Repetition Statement</title> 10 <script type = "text/javascript"> 11 <!-- 12 var counter = 1; do { 15 document.writeln( "<h" + counter + ">This is " + 16 "an h" + counter + " level head" + "</h" + 17 counter + ">" ); 18 ++counter; 19 } while ( counter <= 6 ); 20 // --> 21 </script> </head><body></body> 24 </html> Perform the following actions Then check to see if counter <= 6. If it is, iterate through the loop again. 27 Fig. 8.9 Using the do while repetition statement (Part 1 of 2) Pearson Education, Inc. All rights reserved.

296 28 Fig. 8.9 Using the do while repetition statement (Part 2 of 2).

297 29 Perform an action first If it is true, repeat the action Then check to see if the condition is true Otherwise, exit the loop Fig do while repetition statement flowchart.

298 break and continue Statements break statement in a while, for, do while or switch statement Causes immediate exit from the statement Execution continues with the next statement in sequence break statement common uses Escape early from a loop Skip the remainder of a switch statement

299 8.7 break and continue Statements (Cont.) 31 continue statement in a while, for or do while skips the remaining statements in the body of the statement and proceeds with the next iteration of the loop In while and do while statements, the loopcontinuation test evaluates immediately after the continue statement executes In for statements, the increment expression executes, then the loop-continuation test evaluates

300 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 8.11: BreakTest.html --> 6 <!-- Using the break statement in a for statement. --> 7 <html xmlns = " 8 <head> 9 <title> 10 Using the break Statement in a for Statement 11 </title> 12 <script type = "text/javascript"> 13 <!-- 14 for ( var count = 1; count <= 10; ++count ) 15 { 16 if ( count == 5 ) 17 break; // break loop only if count == document.writeln( "Count is: " + count + "<br />" ); 20 } //end for document.writeln( 23 "Broke out of loop at count = " + count ); 24 // --> 25 </script> 26 </head><body></body> 27 </html> Exits the for loop immediately if count == 5 32 Fig Using the break statement in a for statement (Part 1 of 2) Pearson Education, Inc. All rights reserved.

301 33 Fig Using the break statement in a for statement (Part 2 of 2).

302 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 8.12: ContinueTest.html --> 6 <!-- Using the continue statement in a for statement. --> 7 <html xmlns = " 8 <head> 9 <title> 10 Using the continue Statement in a for Statement 11 </title> <script type = "text/javascript"> 14 <!-- 15 for ( var count = 1; count <= 10; ++count ) 16 { 17 if ( count == 5 ) 18 continue; // skip remaining loop code only if count == document.writeln( "Count is: " + count + "<br />" ); 21 } //end for document.writeln( "Used continue to skip printing 5" ); 24 // --> 25 </script> </head><body></body> 28 </html> If count == 5, skips the rest of the statements in the loop, increments count, and performs the loopcontinuation test Fig Using the continue statement in a for statement (Part 1 of 2) Pearson Education, Inc. All rights reserved.

303 35 Fig Using the continue statement in a for statement (Part 2 of 2).

304 8.8 Labeled break and continue Statements 36 To break out of a nested control statement Use the labeled break statement When executed in a while, for, do while or switch statement, causes immediate exit from that statement and any number of enclosing repetition statements Program execution resumes with the first statement after the specified labeled statement (a statement preceded by a label) A labeled statement can be a block (a set of statements enclosed in curly braces, {}) Commonly are used to terminate nested looping structures containing while, for, do while or switch statements

305 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 8.13: BreakLabelTest.html --> 6 <!-- Labeled break statement in a nested for statement. --> 7 <html xmlns = " 8 <head> 9 <title>using the break Statement with a Label</title> 10 <script type = "text/javascript"> 11 <!-- 12 stop: { // labeled block 13 for ( var row = 1; row <= 10; ++row ) 14 { 15 for ( var column = 1; column <= 5 ; ++column ) 16 { 17 if ( row == 5 ) 18 break stop; // jump to end of stop block document.write( "* " ); 21 } //end for document.writeln( "<br />" ); 24 } //end for // the following line is skipped 27 document.writeln( "This line should not print" ); 28 } // end block labeled stop 29 Statement label Beginning of labeled statement Fig Labeled break statement in a nested for statement (Part 1 of 2). If row == 5, immediately go to the end of the stop block End of labeled statement Pearson Education, Inc. All rights reserved.

306 30 document.writeln( "End of script" ); 31 // --> 32 </script> 33 </head><body></body> 34 </html> Fig Labeled break statement in a nested for statement (Part 2 of 2) Pearson Education, Inc. All rights reserved.

307 8.8 Labeled break and continue Statements (Cont.) 39 Labeled continue statement When executed in a repetition statement (while, for or do while), skips the remaining statements in the structure s body and any number of enclosing repetition statements Proceeds with the next iteration of the specified labeled repetition statement (a repetition statement preceded by a label) In labeled while and do while statements, the loopcontinuation test evaluates immediately after the continue statement executes In a labeled for statement, the increment expression executes, then the loop-continuation test evaluates

308 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 8.14: ContinueLabelTest.html --> 6 <!-- Labeled continue statement in a nested for statement. --> 7 <html xmlns = " 8 <head> 9 <title>using the continue Statement with a Label</title> 10 <script type = "text/javascript"> 11 <!-- 12 nextrow: // target label of continue statement 13 for ( var row = 1; row <= 5; ++row ) 14 { 15 document.writeln( "<br />" ); for ( var column = 1; column <= 10; ++column ) 18 { 19 if ( column > row ) 20 continue nextrow; // next iteration of labeled loop document.write( "* " ); 23 } //end for 24 } //end for 25 // --> 26 </script> 27 </head><body></body> 28 </html> Statement label End of labeled statement Beginning of labeled statement Fig Labeled continue statement in a nested for statement (Part 1 of 2). If column > row, skip all remaining statements in the nextrow block, perform the increment expression, then evaluate the loopcontinuation test Pearson Education, Inc. All rights reserved.

309 41 Fig Labeled continue statement in a nested for statement (Part 2 of 2).

310 Logical Operators Logical operators can be used to form complex conditions by combining simple conditions && (logical AND) (logical OR)! (logical NOT, also called logical negation) The && operator is used to ensure that two conditions are both true before choosing a certain path of execution JavaScript evaluates to false or true all expressions that include relational operators, equality operators and/or logical operators

311 43 Fig Truth table for the && (logical AND) operator expression1 expression2 expression1 && expression2 false false false false true false true false false true true true 2008 Pearson Education, Inc. All rights reserved.

312 Logical Operators (Cont.) The (logical OR) operator is used to ensure that either or both of two conditions are true before choosing choose a certain path of execution

313 45 Fig Truth table for the (logical OR) operator. expression1 expression2 expression1 expression2 false false false false true true true false true true true true 2008 Pearson Education, Inc. All rights reserved.

314 Logical Operators (Cont.) The && operator has a higher precedence than the operator Both operators associate from left to right. An expression containing && or operators is evaluated only until truth or falsity is known This is called short-circuit evaluation

315 Logical Operators (Cont.)! (logical negation) operator reverses the meaning of a condition (i.e., a true value becomes false, and a false value becomes true) Has only a single condition as an operand (i.e., it is a unary operator) Placed before a condition to evaluate to true if the original condition (without the logical negation operator) is false

316 48 Fig Truth table for operator! (logical negation). expression false true!expression true false 2008 Pearson Education, Inc. All rights reserved.

317 Logical Operators (Cont.) Most nonboolean values can be converted to a boolean true or false value Nonzero numeric values are considered to be true The numeric value zero is considered to be false Any string that contains characters is considered to be true The empty string is considered to be false The value null and variables that have been declared but not initialized are considered to be false All objects are considered to be true

318 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 8.18: LogicalOperators.html --> 6 <!-- Demonstrating logical operators. --> 7 <html xmlns = " 8 <head> 9 <title>demonstrating the Logical Operators</title> 10 <style type = "text/css"> 11 table { width: 100% } 12 td.left { width: 25% } 13 </style> 14 <script type = "text/javascript"> 15 <!-- 16 document.writeln( 17 "<table border = \"1\"" ); 18 document.writeln( 19 "<caption>demonstrating Logical " + 20 "Operators</caption>" ); 21 document.writeln( 22 "<tr><td class = \"left\">logical AND (&&)</td>" + 23 "<td>false && false: " + ( false && false ) + 24 "<br />false && true: " + ( false && true ) + 25 "<br />true && false: " + ( true && false ) + 26 "<br />true && true: " + ( true && true ) + 27 "</td></tr>" ); 50 Fig Demonstrating logical operators (Part 1 of 2). Generates a truth table for the logical AND operator 2008 Pearson Education, Inc. All rights reserved.

319 28 document.writeln( 29 "<tr><td class = \"left\">logical OR ( )</td>" + 30 "<td>false false: " + ( false false ) + 31 "<br />false true: " + ( false true ) + 32 "<br />true false: " + ( true false ) + 33 "<br />true true: " + ( true true ) + 34 "</td></tr>" ); 35 document.writeln( 36 "<tr><td class = \"left\">logical NOT (!)</td>" + 37 "<td>!false: " + (!false ) + 38 "<br />!true: " + (!true ) + "</td></tr>" ); 39 document.writeln( "</table>" ); 40 // --> 41 </script> 42 </head><body></body> 43 </html> 51 Fig Demonstrating logical operators (Part 2 of 2). Generates a truth table for the logical OR operator Generates a truth table for the logical NOT operator 2008 Pearson Education, Inc. All rights reserved.

320 52 Fig Precedence and associativity of the operators discussed so far. Operator Associativity Type ++ --! right to left unary * / % left to right multiplicative + - left to right additive < <= > >= left to right relational ==!= left to right equality && left to right logical AND left to right logical OR?: right to left conditional 2008 Pearson Education, Inc. All rights reserved.

321 8.10 Summary of Structured Programming 53 The following charts review some of the key topics of structured programming.

322 54 Fig Single-entry/single-exit sequence, selection and repetition structures.

323 55 Fig Forming rules for structured programs. Rules for forming structured programs 1. Begin with the simplest flowchart (Fig. 8.22). 2. Any rectangle (action) can be replaced by two rectangles (actions) in sequence. 3. Any rectangle (action) can be replaced by any control structure (sequence, if, if else, switch, while, do while or for). 4. Rules 2 and 3 may be applied as often as necessary and in any order Pearson Education, Inc. All rights reserved.

324 56 Begin with this simplest flowchart Fig Simplest flowchart.

325 57 Any rectangle (action) can be replaced by two rectangles (actions) in sequence Fig Repeatedly applying Rule 2 of Fig to the simplest flowchart.

326 58 Any rectangle (action) can be replaced by any control structure Fig Applying Rule 3 of Fig to the simplest flowchart.

327 59 These operations for building blocks are legal This operations for building blocks is illegal Fig Stacked, nested and overlapped building blocks.

328 60 If the rules are followed, this unstructured flowchart cannot be created Fig Unstructured flowchart.

329 1 9 JavaScript: Functions

330 2 9.1 Introduction To develop and maintain a large program construct it from small, simple pieces divide and conquer

331 3 9.2 Program Modules in JavaScript JavaScript programs are written by combining new functions that the programmer writes with prepackaged functions and objects available in JavaScript The term method implies that a function belongs to a particular object We refer to functions that belong to a particular JavaScript object as methods; all others are referred to as functions.

332 9.2 Program Modules in JavaScript (Cont.) 4 JavaScript provides several objects that have a rich collection of methods for performing common mathematical calculations, string manipulations, date and time manipulations, and manipulations of collections of data called arrays. Whenever possible, use existing JavaScript objects, methods and functions instead of writing new ones. This reduces script-development time and helps avoid introducing errors.

333 9.2 Program Modules in JavaScript (Cont.) 5 You can define programmer-defined functions that perform specific tasks and use them at many points in a script The actual statements defining the function are written only once and are hidden from other functions Functions are invoked by writing the name of the function, followed by a left parenthesis, followed by a comma-separated list of zero or more arguments, followed by a right parenthesis Methods are called in the same way as functions, but require the name of the object to which the method belongs and a dot preceding the method name Function (and method) arguments may be constants, variables or expressions

334 6 boss is boss of all workers Worker1 is boss of worker4 and worker5 Worker4 and worker5 report back to worker1 worker1, worker2 and worker3 report back to boss Fig. 9.1 Hierarchical boss-function/worker-function relationship.

335 7 9.3 Programmer-Defined Functions Variables declared in function definitions are local variables they can be accessed only in the function in which they are defined A function s parameters are considered to be local variables When a function is called, the arguments in the call are assigned to the corresponding parameters in the function definition

336 9.3 Programmer-Defined Functions (Cont.) 8 Code that is packaged as a function can be executed from several locations in a program by calling the function. Each function should perform a single, welldefined task, and the name of the function should express that task effectively Promotes software reusability

337 9 9.4 Function Definitions return statement passes information from inside a function back to the point in the program where it was called A function must be called explicitly for the code in its body to execute The format of a function definition is function function-name( parameter-list ) { } declarations and statements

338 Function Definitions (Cont.) Three ways to return control to the point at which a function was invoked Reaching the function-ending right brace Executing the statement return; Executing the statement return expression; to return the value of expression to the caller When a return statement executes, control returns immediately to the point at which the function was invoked

339 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 9.2: SquareInt.html --> 6 <!-- Programmer-defined function square. --> 7 <html xmlns = " 8 <head> 9 <title>a Programmer-Defined square Function</title> 10 <script type = "text/javascript"> 11 <!-- 12 document.writeln( "<h1>square the numbers from 1 to 10</h1>" ); // square the numbers from 1 to for ( var x = 1; x <= 10; x++ ) 16 document.writeln( "The square of " + x + " is " + 17 square( x ) + "<br />" ); // The following square function definition is executed 20 // only when the function is explicitly called // square function definition 23 function square( y ) 24 { 25 return y * y; 26 } // end function square 27 // --> 28 </script> 29 </head><body></body> 30 </html> End function square Names the parameter y Begin function square 11 Fig. 9.2 Programmerdefined function square (Part 1 of 2). Calls function square with x as an argument, which will return the value to be inserted here Returns the value of y * y (the argument squared) to the caller 2008 Pearson Education, Inc. All rights reserved.

340 12 Fig. 9.2 Programmer-defined function square (Part 2 of 2).

341 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 9.3: maximum.html --> 6 <!-- Programmer-Defined maximum function. --> 7 <html xmlns = " 8 <head> 9 <title>finding the Maximum of Three Values</title> 10 <script type = "text/javascript"> 11 <!-- 12 var input1 = window.prompt( "Enter first number", "0" ); 13 var input2 = window.prompt( "Enter second number", "0" ); 14 var input3 = window.prompt( "Enter third number", "0" ); var value1 = parsefloat( input1 ); 17 var value2 = parsefloat( input2 ); 18 var value3 = parsefloat( input3 ); 19 Creates integer values from user input 13 Fig. 9.3 Programmerdefined maximum function (Part 1 of 3) Pearson Education, Inc. All rights reserved.

342 20 var maxvalue = maximum( value1, value2, value3 ); document.writeln( "First number: " + value "<br />Second number: " + value "<br />Third number: " + value "<br />Maximum is: " + maxvalue ); // maximum function definition (called from line 20) 28 function maximum( x, y, z ) 29 { 30 return Math.max( x, Math.max( y, z ) ); 31 } // end function maximum 32 // --> 33 </script> 34 </head> 35 <body> 36 <p>click Refresh (or Reload) to run the script again</p> 37 </body> 38 </html> End function maximum Calls function maximum with arguments value1, value2 and value3 Begin function maximum with local variables x, y and z 14 Fig. 9.3 Programmerdefined maximum function (Part 2 of 3). Calls the Math object s method max to compare the first variable with the maximum of the other two Variable maxvalue stores the return value of the call to maximum 2008 Pearson Education, Inc. All rights reserved.

343 15 Fig. 9.3 Programmer-defined maximum function (Part 3 of 3).

344 Random Number Generation Method random generates a floating-point value from 0.0 up to, but not including, 1.0 Random integers in a certain range can be generated by scaling and shifting the values returned by random, then using Math.floor to convert them to integers The scaling factor determines the size of the range (i.e. a scaling factor of 4 means four possible integers) The shift number is added to the result to determine where the range begins (i.e. shifting the numbers by 3 would give numbers between 3 and 7) Method Math.floor rounds its argument down to the closest integer

345 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 9.4: RandomInt.html --> 6 <!-- Random integers, shifting and scaling. --> 7 <html xmlns = " 8 <head> 9 <title>shifted and Scaled Random Integers</title> 10 <style type = "text/css"> 11 table { width: 50%; 12 border: 1px solid gray; 13 text-align: center } 14 </style> 15 <script type = "text/javascript"> 16 <!-- 17 var value; document.writeln( "<table>" ); 20 document.writeln( "<caption>random Numbers</caption><tr>" ); for ( var i = 1; i <= 20; i++ ) 23 { 24 value = Math.floor( 1 + Math.random() * 6 ); 25 document.writeln( "<td>" + value + "</td>" ); // start a new table row every 5 entries 28 if ( i % 5 == 0 && i!= 20 ) 29 document.writeln( "</tr><tr>" ); 30 } // end for 31 Shifts the range of return values up by 1 Scales the range of return values by a factor of 6 17 Fig. 9.4 Random integers, shifting and scaling (Part 1 of 2). Takes the floor of the number from 1.0 up to, but not including, Pearson Education, Inc. All rights reserved.

346 32 document.writeln( "</tr></table>" ); 33 // --> 34 </script> 35 </head> 36 <body> 37 <p>click Refresh (or Reload) to run the script again</p> 38 </body> 39 </html> 18 Fig. 9.4 Random integers, shifting and scaling (Part 2 of 2). Variable value has a value from 1 to Pearson Education, Inc. All rights reserved.

347 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 9.5: RollDie.html --> 6 <!-- Rolling a Six-Sided Die 6000 times. --> 7 <html xmlns = " 8 <head> 9 <title>roll a Six-Sided Die 6000 Times</title> 10 <script type = "text/javascript"> 11 <!-- 12 var frequency1 = 0; 13 var frequency2 = 0; 14 var frequency3 = 0; 15 var frequency4 = 0; 16 var frequency5 = 0; 17 var frequency6 = 0; 18 var face; // roll die 6000 times and accumulate results 21 for ( var roll = 1; roll <= 6000; roll++ ) 22 { 23 face = Math.floor( 1 + Math.random() * 6 ); switch ( face ) 26 { 27 case 1: 28 ++frequency1; 29 break; 19 Fig. 9.5 Rolling a six-sided die 6000 times (Part 1 of 3). Stores a random integer in the range 1 6 to variable face Uses a switch statement to process the results 2008 Pearson Education, Inc. All rights reserved.

348 30 case 2: 31 ++frequency2; 32 break; 33 case 3: 34 ++frequency3; 35 break; 36 case 4: 37 ++frequency4; 38 break; 39 case 5: 40 ++frequency5; 41 break; 42 case 6: 43 ++frequency6; 44 break; 45 } // end switch 46 } // end for document.writeln( "<table border = \"1\">" ); 49 document.writeln( "<thead><th>face</th>" + 50 "<th>frequency</th></thead>" ); 51 document.writeln( "<tbody><tr><td>1</td><td>" + 52 frequency1 + "</td></tr>" ); 53 document.writeln( "<tr><td>2</td><td>" + frequency "</td></tr>" ); 55 document.writeln( "<tr><td>3</td><td>" + frequency "</td></tr>" ); 57 document.writeln( "<tr><td>4</td><td>" + frequency "</td></tr>" ); 20 Fig. 9.5 Rolling a six-sided die 6000 times (Part 2 of 3). Outputs the number of occurrences of each face being rolled 2008 Pearson Education, Inc. All rights reserved.

349 59 document.writeln( "<tr><td>5</td><td>" + frequency "</td></tr>" ); 61 document.writeln( "<tr><td>6</td><td>" + frequency "</td></tr></tbody></table>" ); 63 // --> 64 </script> 65 </head> 66 <body> 67 <p>click Refresh (or Reload) to run the script again</p> 68 </body> 69 </html> 21 Fig. 9.5 Rolling a six-sided die 6000 times (Part 3 of 3). Running the script another time calls Math.random again and (usually) results in different frequencies 2008 Pearson Education, Inc. All rights reserved.

350 Example: Game of Chance JavaScript can execute actions in response to the user s interaction with a GUI component in an XHTML form. This is referred to as GUI event handling An XHTML element s onclick attribute indicates the action to take when the user of the XHTML document clicks on the element In event-driven programming the user interacts with a GUI component the script is notified of the event the script processes the event The user s interaction with the GUI drives the program. The function that is called when an event occurs is known as an event-handling function or event handler.

351 9.6 Example: Game of Chance (Cont.) 23 The getelementbyid method, given an id as an argument, finds the XHTML element with a matching id attribute and returns a JavaScript object representing the element The value property of a JavaScript object representing an XHTML text input element specifies the text to display in the text field An XHTML container (e.g. div, span, p) element s innerhtml property can be used in a script to set the contents of the element

352 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 9.6: Craps.html --> 6 <!-- Craps game simulation. --> 7 <html xmlns = " 8 <head> 9 <title>program that Simulates the Game of Craps</title> 10 <style type = "text/css"> 11 table { text-align: right } 12 body { font-family: arial, sans-serif } 13 div.red { color: red } 14 </style> 15 <script type = "text/javascript"> 16 <!-- 17 // variables used to test the state of the game 18 var WON = 0; 19 var LOST = 1; 20 var CONTINUE_ROLLING = 2; // other variables used in program 23 var firstroll = true; // true if current roll is first 24 var sumofdice = 0; // sum of the dice 25 var mypoint = 0; // point if no win/loss on first roll 26 var gamestatus = CONTINUE_ROLLING; // game not over yet // process one roll of the dice 29 function play() 30 { 24 Fig. 9.6 Craps game simulation (Part 1 of 6) Pearson Education, Inc. All rights reserved.

353 31 // get the point field on the page 32 var point = document.getelementbyid( "pointfield" ); // get the status div on the page 35 var statusdiv = document.getelementbyid( "status" ); 36 if ( firstroll ) // first roll of the dice 37 { 38 sumofdice = rolldice(); switch ( sumofdice ) 41 { 42 case 7: case 11: // win on first roll 43 gamestatus = WON; 44 // clear point field 45 point.value = ""; 46 break; 47 case 2: case 3: case 12: // lose on first roll 48 gamestatus = LOST; 49 // clear point field 50 point.value = ""; 51 break; 52 default: // remember point 53 gamestatus = CONTINUE_ROLLING; 54 mypoint = sumofdice; 55 point.value = mypoint; 56 firstroll = false; 57 } // end switch 58 } // end if 59 else 60 { 25 Fig. 9.6 Craps game simulation (Part 2 of 6). statusdiv holds the object with status as its id switch statement performs actions for specific dice values 2008 Pearson Education, Inc. All rights reserved.

354 61 sumofdice = rolldice(); if ( sumofdice == mypoint ) // win by making point 64 gamestatus = WON; 65 else 66 if ( sumofdice == 7 ) // lose by rolling 7 67 gamestatus = LOST; 68 } // end else if ( gamestatus == CONTINUE_ROLLING ) 71 statusdiv.innerhtml = "Roll again"; 72 else 73 { 74 if ( gamestatus == WON ) 75 statusdiv.innerhtml = "Player wins. " + 76 "Click Roll Dice to play again."; 77 else 78 statusdiv.innerhtml = "Player loses. " + 79 "Click Roll Dice to play again."; firstroll = true; 82 } // end else 83 } // end function play // roll the dice 86 function rolldice() 87 { 88 var die1; 89 var die2; 90 var worksum; Fig. 9.6 Craps game simulation (Part 3 of 6). Sets the contents of the statusdiv object to Roll Again Sets the contents of the statusdiv object to Player wins. Click Roll Dice to play again. Sets the contents of the statusdiv object to Player loses. Click Roll Dice to play again Pearson Education, Inc. All rights reserved.

355 92 die1 = Math.floor( 1 + Math.random() * 6 ); 93 die2 = Math.floor( 1 + Math.random() * 6 ); 94 worksum = die1 + die2; document.getelementbyid( "die1field" ).value = die1; 97 document.getelementbyid( "die2field" ).value = die2; 98 document.getelementbyid( "sumfield" ).value = worksum; return worksum; 101 } // end function rolldice 102 // --> 103 </script> 104 </head> 105 <body> 106 <form action = ""> 107 <table> 108 <caption>craps</caption> 109 <tr><td>die 1</td> 110 <td><input id = "die1field" type = "text" /> 111 </td></tr> 112 <tr><td>die 2</td> 113 <td><input id = "die2field" type = "text" /> 114 </td></tr> 115 <tr><td>sum</td> 116 <td><input id = "sumfield" type = "text" /> 117 </td></tr> 118 <tr><td>point</td> 119 <td><input id = "pointfield" type = "text" /> 120 </td></tr> Sets the id fields of these container objects so that they can be retrieved by getelementbyid in the script 27 Fig. 9.6 Craps game simulation (Part 4 of 6). Sets the values of the die1field, die2field and sumfield objects to die1, die2 and worksum, respectively 2008 Pearson Education, Inc. All rights reserved.

356 121 <tr><td /><td><input type = "button" value = "Roll Dice" 122 onclick = "play()" /></td></tr> 123 </table> 124 <div id = "status" class = "red"> 125 Click the Roll Dice button to play</div> 126 </form> 127 </body> 128 </html> When the Roll Dice button is clicked, function play is called 28 Fig. 9.6 Craps game simulation (Part 5 of 6) Pearson Education, Inc. All rights reserved.

357 29 Fig. 9.6 Craps game simulation (Part 6 of 6) Pearson Education, Inc. All rights reserved.

358 9.7 Another Example: Random Image Generator 30 We can use random number generation to randomly select from a number of images in order to display a random image each time a page loads

359 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 9.7: RandomPicture.html --> 6 <!-- Random image generation using Math.random. --> 7 <html xmlns = " 8 <head> 9 <title>random Image Generator</title> 10 <script type = "text/javascript"> 11 <!-- 12 document.write ( "<img src = \"" + 13 Math.floor( 1 + Math.random() * 7 ) + ".gif\" />" ); 14 // --> 15 </script> 16 </head> 17 <body> 18 <p>click Refresh (or Reload) to run the script again</p> 19 </body> 20 </html> Fig. 9.7 Random image generation using Math.random. Creates an src attribute by concatenating a random integer from 1 to 7 with.gif\ to reference one of the images 1.gif, 2.gif, 3.gif, 4.gif, 5.gif, 6.gif or 7.gif Pearson Education, Inc. All rights reserved.

360 Scope Rules Each identifier in a program has a scope The scope of an identifier for a variable or function is the portion of the program in which the identifier can be referenced Global variables or script-level are accessible in any part of a script and are said to have global scope Thus every function in the script can potentially use the variables

361 Scope Rules (Cont.) Identifiers declared inside a function have function (or local) scope and can be used only in that function Function scope begins with the opening left brace ({) of the function in which the identifier is declared and ends at the terminating right brace (}) of the function Local variables of a function and function parameters have function scope If a local variable in a function has the same name as a global variable, the global variable is hidden from the body of the function.

362 Scope Rules (Cont.) onload property of the body element calls an event handler when the <body> of the XHTML document is completely loaded into the browser window

363 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 9.8: scoping.html --> 6 <!-- Scoping example. --> 7 <html xmlns = " 8 <head> 9 <title>a Scoping Example</title> 10 <script type = "text/javascript"> 11 <!-- 12 var x = 1; // global variable function start() 15 { 16 var x = 5; // variable local to function start document.writeln( "local x in start is " + x ); functiona(); // functiona has local x 21 functionb(); // functionb uses global variable x 22 functiona(); // functiona reinitializes local x 23 functionb(); // global variable x retains its value document.writeln( 26 "<p>local x in start is " + x + "</p>" ); 27 } // end function start 28 Global variable declaration Local variable in function start 35 Fig. 9.8 Scoping example (Part 1 of 3) Pearson Education, Inc. All rights reserved.

364 29 function functiona() 30 { 31 var x = 25; // initialized each time 32 // functiona is called document.writeln( "<p>local x in functiona is " + 35 x + " after entering functiona" ); 36 ++x; 37 document.writeln( "<br />local x in functiona is " + 38 x + " before exiting functiona" + "</p>" ); 39 } // end functiona function functionb() 42 { 43 document.writeln( "<p>global variable x is " + x + 44 " on entering functionb" ); 45 x *= 10; 46 document.writeln( "<br />global variable x is " + 47 x + " on exiting functionb" + "</p>" ); 48 } // end functionb 49 // --> 50 </script> 51 </head> 52 <body onload = "start()"></body> 53 </html> Local variable in function functiona, initialized each time functiona is called Calls function start when the body of the document has loaded into the browser window 36 Fig. 9.8 Scoping example (Part 2 of 3) Pearson Education, Inc. All rights reserved.

365 37 Fig. 9.8 Scoping example (Part 3 of 3).

366 JavaScript Global Functions JavaScript provides seven global functions as part of a Global object This object contains all the global variables in the script all the user-defined functions in the script all the built-in global functions listed in the following slide You do not need to use the Global object directly; JavaScript uses it for you

367 Global function escape eval isfinite isnan parsefloat parseint Description Fig. 9.9 JavaScript global functions. Takes a string argument and returns a string in which all spaces, punctuation, accent characters and any other character that is not in the ASCII character set (see Appendix D, ASCII Character Set) are encoded in a hexadecimal format (see Appendix E, Number Systems) that can be represented on all platforms. Takes a string argument representing JavaScript code to execute. The JavaScript interpreter evaluates the code and executes it when the eval function is called. This function allows JavaScript code to be stored as strings and executed dynamically. [Note: It is considered a serious security risk to use eval to process any data entered by a user because a malicious user could exploit this to run dangerous code.] Takes a numeric argument and returns true if the value of the argument is not NaN, Number.POSITIVE_INFINITY or Number.NEGATIVE_INFINITY (values that are not numbers or numbers outside the range that JavaScript supports) otherwise, the function returns false. Takes a numeric argument and returns true if the value of the argument is not a number; otherwise, it returns false. The function is commonly used with the return value of parseint or parsefloat to determine whether the result is a proper numeric value. Takes a string argument and attempts to convert the beginning of the string into a floating-point value. If the conversion is unsuccessful, the function returns NaN; otherwise, it returns the converted value (e.g., parsefloat( "abc123.45" ) returns NaN, and parsefloat( "123.45abc" ) returns the value ). Takes a string argument and attempts to convert the beginning of the string into an integer value. If the conversion is unsuccessful, the function returns NaN; otherwise, it returns the converted value (e.g., parseint( "abc123" ) returns NaN, and parseint( "123abc" ) returns the integer value 123). This function takes an optional second argument, from 2 to 36, specifying the radix (or base) of the number. Base 2 indicates that the first argument string is in binary format, base 8 indicates that the first argument string is in octal format and base 16 indicates that the first argument string is in hexadecimal format. See Appendix E, Number Systems, for more information on binary, octal and hexadecimal numbers. 39 unescape Takes a string as its argument and returns a string in which all characters previously encoded with 2008 Pearson Education, escape are decoded. Inc. All rights reserved.

368 Recursion A recursive function calls itself, either directly, or indirectly through another function. A recursive function knows how to solve only the simplest case, or base case If the function is called with a base case, it returns a result If the function is called with a more complex problem, it divides the problem into two conceptual pieces a piece that the function knows how to process (the base case) and a simpler or smaller version of the original problem. The function invokes (calls) a fresh copy of itself to go to work on the smaller problem; this invocation is referred to as a recursive call, or the recursion step.

369 Recursion (Cont.) The recursion step executes while the original call to the function is still open (i.e., it has not finished executing) For recursion eventually to terminate, each time the function calls itself with a simpler version of the original problem, the sequence of smaller and smaller problems must converge on the base case At that point, the function recognizes the base case, returns a result to the previous copy of the function, and a sequence of returns ensues up the line until the original function call eventually returns the final result to the caller

370 42 While the number to be processed is greater than 1, the function calls itself When the number is 1 or less (the base case), 1 is returned, and each function call can now return an answer until each call has been resolved Fig Recursive evaluation of 5!.

371 1 <?xml version = "1.0" encoding = "utf-8"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 9.11: FactorialTest.html --> 6 <!-- Factorial calculation with a recursive function. --> 7 <html xmlns = " 8 <head> 9 <title>recursive Factorial Function</title> 10 <script type = "text/javascript"> 11 <!-- 12 document.writeln( "<h1>factorials of 1 to 10</h1>" ); 13 document.writeln( "<table>" ); for ( var i = 0; i <= 10; i++ ) 16 document.writeln( "<tr><td>" + i + "!</td><td>" + 17 factorial( i ) + "</td></tr>" ); document.writeln( "</table>" ); // Recursive definition of function factorial 22 function factorial( number ) 23 { 24 if ( number <= 1 ) // base case 25 return 1; 26 else 27 return number * factorial( number - 1 ); 28 } // end function factorial 29 // --> 30 </script> 31 </head><body></body> Calls function factorial with argument i Base case Fig Factorial calculation with a recursive function (Part 1 of 2). While the base case is not reached, return the number * ( number 1 )!, which is number * factorial ( number 1 ) factorial calls itself with a new argument and waits until this new value is returned before returning a value itself Pearson Education, Inc. All rights reserved.

372 44 Fig Factorial calculation with a recursive function (Part 2 of 2).

373 Recursion vs. Iteration Both iteration and recursion involve repetition Iteration explicitly uses a repetition statement Recursion achieves repetition through repeated function calls Iteration and recursion each involve a termination test Iteration terminates when the loop-continuation condition fails Recursion terminates when a base case is recognized

374 Recursion vs. Iteration Iteration with counter-controlled repetition and recursion both gradually approach termination Iteration keeps modifying a counter until the counter assumes a value that makes the loop-continuation condition fail Recursion keeps producing simpler versions of the original problem until the base case is reached Recursion repeatedly invokes the mechanism and, consequently, the overhead of function calls expensive in terms of processor time and memory space Some problems can be understood or solved more easily with recursion than with iteration

375 CS230 Internet Technology Quiz2 Name: 1. What does CSS stand for? a. Creative Style Sheets b. Colorful Style Sheets c. Computer Style Sheets d. Cascading Style Sheets 2. What is the correct HTML for referring to an external style sheet? a. <link rel="stylesheet" type="text/css" href="mystyle.css"> b. <style src="mystyle.css" /> c. <stylesheet>mystyle.css</stylesheet /> d. None of the above 3. Where in an HTML document is the correct place to refer to an external style sheet? a. In the <head> section b. In the <body> section c. At the end of the document d. At the top of the document 4. Which HTML tag is used to define an internal style sheet? a. <style> b. <script> c. <css> d. None of the above 5. Which HTML attribute is used to define inline styles? a. font b. class c. style d. styles 6. Which is the correct CSS syntax? a. body:color=black b. {body;color:black} c. {body:color=black(body} d. body {color: black} 7. Which property is used to change the background color? a. color: b. background-color: c. bgcolor: d. None of the above 8. How do you add a background color for all <h1> elements? a. h1 {background-color:#ffffff} b. all.h1 {background-color:#ffffff} c. h1.all {background-color:#ffffff} d. None of the above 9. How do you change the text color of an element? a. text-color: b. color: c.text-color= d. fgcolor: 10. Which CSS property controls the text size? a. font-size b. font-style c. text-style d. text-size

376

377 College of Arts and Sciences Department of Mathematical and Physical Sciences Computer Science Section Spring 2010/ 2011 Semester FIRST EXAM COMP 230 Internet Technology Student Name: Student ID: Date: Apr 4, 2011 Time: P.M. Venue: 4-19 Faculty: Mr. Ahmad Jawdat With our Best Wishes..... Computer Science Section 1

378 University of Nizwa Exam Instructions 1. Students must remain seated and maintain silence, in the examination room. 2. No student is permitted to leave the examination room within the first 30 minutes of the examination. 3. No student will be permitted to enter after 30 minutes of commencement of examination. 4. Upon leaving the exam room, the student is not allowed to enter again for any reason. 5. Immediately after taking your seat, fill in the information required on the Answer Booklet. 6. Students must sign the attendance sheet provided by the invigilators. 7. Students must show his/her ID with photo to the invigilator when requested and when signing in. 8. All belongings, not necessary related to the examination paper, must be suitably placed as directed by the invigilator. 9. Students are not allowed to have their mobile/cell phones with them in the examination room. Mobile/cell phones must be switched off at all times and suitably placed on the front table or as directed by the invigilator. Disciplinary action will be taken against a student who breaches this regulation. 10. Students must carefully read the instructions printed on each answer booklet and examination question paper. 11. Students are not allowed to remove any page from the answer booklet. 12. Students are to answer in approved course language and write in blue or black ink unless the examination paper gives other instructions. 13. Calculators (programmable) and/or electronic dictionaries are not permitted in examination rooms unless authorized by the examiner/invigilator. 14. Students may cancel any written solution(s) by crossing the solution(s) out and writing over it the word CANCELLED clearly. Cancelled solution(s) by students will not be marked even if the written material is correct. 15. A student shall not during an examination session communicate verbally or otherwise with any other person except the invigilator, or assist or communicate with any other person, or willingly receive communication from any person other than the invigilator. 16. A student shall not cheat, attempt to cheat or assist any other student to cheat in an examination. Any student found cheating or assisting another student in cheating may be penalized with a failed grade and/or suspension from the University of Nizwa according to University misconduct regulations. 17. A student suspected by the invigilator of cheating, attempting to cheat or assisting another student to cheat must surrender that material suspected of being used for the purpose of cheating to the invigilator. The invigilator will be required to request the student surrender all material, search belongings and any other material on suspicion of copying or cheating. 18. If the student has accidentally brought revision notes or other unauthorized material into the examination room, he/she must hand them over to the invigilator before the start of the exam. No disciplinary action will be taken against him/her in such a case. 19. At any time, the invigilator may direct a student to move from their seat to another seat specified by the invigilator, and the student must comply without delay and in silence with the instruction. 20. A student must not remove from the examination room any examination paper, rough notes, paper provided for use during the examination, or any other material that is property of the University of Nizwa. All such material must be surrendered to the invigilator at the conclusion of the examination. 21. If, in the opinion of the examination invigilator, a student s behavior is such as to disturb or distract any other student, the invigilator may require the person to leave the examination room and he/she will be penalized by the disciplinary committee at the University of Nizwa 22. Food and drink are not permitted in the examination room (with the exception of water). 23. Students must write clearly; unreadable answers will not be marked. 24. Students must identify each answer clearly with the number of the questions and use both sides of paper if needed. 25. You must hand in your question and answer booklet to the supervisor before you leave the room. 26. Students must remain seated until all examination booklets and answer booklets are collected, counted and checked. Students must remain seated and silent until instructed to leave the examination room. 27. Results may be withheld due to pending any fee payments/library fines/returning textbook/filling teaching evaluation etc. 2

379 Q1: Write the XHTML code to build the following table (6 Marks). Highest Percents of Car Sales Year\Model Nissan Toyota Maxima 22% Corolla 32% 2011 Altima 19% Camry 18% 3

380 Q2: Write the XHTML code to build the following Form (8 Marks). 4

381 5

382 Q3: Using RSA Algorithm, If you know that m=9, e=3, d=7 and n=33 (6 Marks): 1- Write the RSA Algorithm. 2- Calculate c: 3- If you given c=17 calculate m: 6

383 College of Arts and Sciences Department of Mathematical and Physical Sciences Computer Science Section Spring 2010/ 2011 Semester SECOND EXAM COMP 230 Internet Technology Student Name: Student ID: Date: May 14, 2011 Time: P.M. Venue: 4-19 Faculty: Mr. Ahmad Jawdat With our Best Wishes..... Computer Science Section 1

384 University of Nizwa Exam Instructions 1. Students must remain seated and maintain silence, in the examination room. 2. No student is permitted to leave the examination room within the first 30 minutes of the examination. 3. No student will be permitted to enter after 30 minutes of commencement of examination. 4. Upon leaving the exam room, the student is not allowed to enter again for any reason. 5. Immediately after taking your seat, fill in the information required on the Answer Booklet. 6. Students must sign the attendance sheet provided by the invigilators. 7. Students must show his/her ID with photo to the invigilator when requested and when signing in. 8. All belongings, not necessary related to the examination paper, must be suitably placed as directed by the invigilator. 9. Students are not allowed to have their mobile/cell phones with them in the examination room. Mobile/cell phones must be switched off at all times and suitably placed on the front table or as directed by the invigilator. Disciplinary action will be taken against a student who breaches this regulation. 10. Students must carefully read the instructions printed on each answer booklet and examination question paper. 11. Students are not allowed to remove any page from the answer booklet. 12. Students are to answer in approved course language and write in blue or black ink unless the examination paper gives other instructions. 13. Calculators (programmable) and/or electronic dictionaries are not permitted in examination rooms unless authorized by the examiner/invigilator. 14. Students may cancel any written solution(s) by crossing the solution(s) out and writing over it the word CANCELLED clearly. Cancelled solution(s) by students will not be marked even if the written material is correct. 15. A student shall not during an examination session communicate verbally or otherwise with any other person except the invigilator, or assist or communicate with any other person, or willingly receive communication from any person other than the invigilator. 16. A student shall not cheat, attempt to cheat or assist any other student to cheat in an examination. Any student found cheating or assisting another student in cheating may be penalized with a failed grade and/or suspension from the University of Nizwa according to University misconduct regulations. 17. A student suspected by the invigilator of cheating, attempting to cheat or assisting another student to cheat must surrender that material suspected of being used for the purpose of cheating to the invigilator. The invigilator will be required to request the student surrender all material, search belongings and any other material on suspicion of copying or cheating. 18. If the student has accidentally brought revision notes or other unauthorized material into the examination room, he/she must hand them over to the invigilator before the start of the exam. No disciplinary action will be taken against him/her in such a case. 19. At any time, the invigilator may direct a student to move from their seat to another seat specified by the invigilator, and the student must comply without delay and in silence with the instruction. 20. A student must not remove from the examination room any examination paper, rough notes, paper provided for use during the examination, or any other material that is property of the University of Nizwa. All such material must be surrendered to the invigilator at the conclusion of the examination. 21. If, in the opinion of the examination invigilator, a student s behavior is such as to disturb or distract any other student, the invigilator may require the person to leave the examination room and he/she will be penalized by the disciplinary committee at the University of Nizwa 22. Food and drink are not permitted in the examination room (with the exception of water). 23. Students must write clearly; unreadable answers will not be marked. 24. Students must identify each answer clearly with the number of the questions and use both sides of paper if needed. 25. You must hand in your question and answer booklet to the supervisor before you leave the room. 26. Students must remain seated until all examination booklets and answer booklets are collected, counted and checked. Students must remain seated and silent until instructed to leave the examination room. 27. Results may be withheld due to pending any fee payments/library fines/returning textbook/filling teaching evaluation etc. 2

385 Q1: 1- Write the code for "ex2.css" that gives the following output. (4 Marks) Color is red Color is navy Color is tan Margin left 15 and size 11 Color is green When you move the mouse over it the color is green and no underline When you visit the link it will be blue 3

386 2- Write one line sentence how to do the following using CSS: (3 Marks) 1- Make an ordered list appears using (I, II, III, ) 2- Format the following table Borders and header background colors are green. 4

387 Q2: Write a script that reads a number and outputs XHTML text that displays in the XHTML document a checkerboard pattern as follows (6 Marks). i.e. x=5 * * * * * * * * * * * * * * * * * * * * * * * * * 5

388 Q3: Write a script that calculates the squares and cubes of the numbers from 0 to 10 and outputs XHTML text that display the resulting values in an XHTML table format: as follows: (6 Marks): number square cube

389 College of Arts and Sciences Department of Mathematical and Physical Sciences Computer Science Section Spring 2010/ 2011 Semester FINAL EXAM COMP 230 Internet Technology Student Name: Student ID: Date: Jun 1, 2011 Time: A.M. Venue: 4-5 Faculty: Mr. Ahmad Jawdat With our Best Wishes..... Computer Science Section 1

390 Student s Name:... Student s I.D. Number:... Student s Signature:. Date: ANSWER BOOKLET Question Number Maximum Marks Obtained Mark Numerical Words Total Marks 40 Graded By: Mr. Ahmad Jawdat Signature: Checked By: Dr. Fathi Tanzakhti Signature: 2

391 University of Nizwa Exam Instructions 1. Students must remain seated and maintain silence, in the examination room. 2. No student is permitted to leave the examination room within the first 30 minutes of the examination. 3. No student will be permitted to enter after 30 minutes of commencement of examination. 4. Upon leaving the exam room, the student is not allowed to enter again for any reason. 5. Immediately after taking your seat, fill in the information required on the Answer Booklet. 6. Students must sign the attendance sheet provided by the invigilators. 7. Students must show his/her ID with photo to the invigilator when requested and when signing in. 8. All belongings, not necessary related to the examination paper, must be suitably placed as directed by the invigilator. 9. Students are not allowed to have their mobile/cell phones with them in the examination room. Mobile/cell phones must be switched off at all times and suitably placed on the front table or as directed by the invigilator. Disciplinary action will be taken against a student who breaches this regulation. 10. Students must carefully read the instructions printed on each answer booklet and examination question paper. 11. Students are not allowed to remove any page from the answer booklet. 12. Students are to answer in approved course language and write in blue or black ink unless the examination paper gives other instructions. 13. Calculators (programmable) and/or electronic dictionaries are not permitted in examination rooms unless authorized by the examiner/invigilator. 14. Students may cancel any written solution(s) by crossing the solution(s) out and writing over it the word CANCELLED clearly. Cancelled solution(s) by students will not be marked even if the written material is correct. 15. A student shall not during an examination session communicate verbally or otherwise with any other person except the invigilator, or assist or communicate with any other person, or willingly receive communication from any person other than the invigilator. 16. A student shall not cheat, attempt to cheat or assist any other student to cheat in an examination. Any student found cheating or assisting another student in cheating may be penalized with a failed grade and/or suspension from the University of Nizwa according to University misconduct regulations. 17. A student suspected by the invigilator of cheating, attempting to cheat or assisting another student to cheat must surrender that material suspected of being used for the purpose of cheating to the invigilator. The invigilator will be required to request the student surrender all material, search belongings and any other material on suspicion of copying or cheating. 18. If the student has accidentally brought revision notes or other unauthorized material into the examination room, he/she must hand them over to the invigilator before the start of the exam. No disciplinary action will be taken against him/her in such a case. 19. At any time, the invigilator may direct a student to move from their seat to another seat specified by the invigilator, and the student must comply without delay and in silence with the instruction. 20. A student must not remove from the examination room any examination paper, rough notes, paper provided for use during the examination, or any other material that is property of the University of Nizwa. All such material must be surrendered to the invigilator at the conclusion of the examination. 21. If, in the opinion of the examination invigilator, a student s behavior is such as to disturb or distract any other student, the invigilator may require the person to leave the examination room and he/she will be penalized by the disciplinary committee at the University of Nizwa 22. Food and drink are not permitted in the examination room (with the exception of water). 23. Students must write clearly; unreadable answers will not be marked. 24. Students must identify each answer clearly with the number of the questions and use both sides of paper if needed. 25. You must hand in your question and answer booklet to the supervisor before you leave the room. 26. Students must remain seated until all examination booklets and answer booklets are collected, counted and checked. Students must remain seated and silent until instructed to leave the examination room. 27. Results may be withheld due to pending any fee payments/library fines/returning textbook/filling teaching evaluation etc. 3

392 Q1: Choose the correct answer: (15 marks) 1- Who is making the Web standards? a- Mozilla b- The World Wide Web Consortium c- Microsoft d- All answers are true 2- What is the preferred way for adding a background color in HTML? a- <body style="background-color:yellow"> b- <background>yellow</background> c- <body background="yellow"> d- None of the above. 3- Which of these tags are all <table> tags? a- <table><tr><tt> b- <table><tr><td> c- <table><head><tfoot> d- <thead><body><tr> 4- What is the correct HTML for making a checkbox? a- <checkbox> b- <input type="checkbox" /> c- <check> d- <input type="check" /> 5- What is the correct HTML for making a drop-down list? a- <input type="list" /> b- <input type="dropdown" /> c- <list> d- <select> 6- What is the correct HTML for inserting an image? a- <img src="image.gif" alt="myimage" /> b- <image src="image.gif" alt="myimage" /> c- <img alt="myimage">image.gif</img> d- <img href="image.gif" alt="myimage" /> 4

393 7- What does XHTML stand for? a- EXtra Hyperlinks and Text Markup Language b- EXtreme HyperText Markup Language c- EXtensible HyperText Marking Language d- EXtensible HyperText Markup Language 8- What is the correct XHTML for an attribute and its value? a- WIDTH=80 b- WIDTH="80" c- width=80 d- width="80" 9- What XHTML code is "well-formed"? a- <p>a <b><i>short</i></b> paragraph b- <p>a <b><i>short</i></b> paragraph</p> c- <p>a <b><i>short</b></i> paragraph</p> d- All answers are true Questions are related to Java Script. 10- Inside which HTML element do we put the JavaScript? a- <javascript> b- <scripting> c- <js> d- <script> 11- What is the correct JavaScript syntax to write "Hello World"? a- document.write("hello World") b- "Hello World" c- ("Hello World") d- response.write("hello World") 12- How do you write "Hello World" in an alert box? a- alertbox="hello World" b- msgbox("hello World") c- alert("hello World") d- alertbox("hello World") 5

394 13- How do you create a function? a- function myfunction() b- function:myfunction() c- function=myfunction() d- All answers are true 14-How do you write a conditional statement for executing some code if "i" is equal to 5? a- if (i=5) b- if (i==5) then c- if (i=5 then) d- if (i==5) 15- How does a "for" loop start? a- for (i <= 5; i++) b- for (i = 0; i <= 5; i++) c- for i = 1 to 5 d- for (i = 0; i <= 5) 16- What is the correct JavaScript syntax to insert a comment that has more than one line? a- /*This is a comment */ b- / This is a comment c- <!-- This is a comment --> d- All answers are true 17- How do you find the number with x to the power y? a- power(x,y) b- exp(x,y) c- Math.power(x,y) d- Math.exp(x,y) 18- What does CSS stand for? a- Creative Style Sheets b- Colorful Style Sheets c- Computer Style Sheets d- Cascading Style Sheets 6

395 19- What is the correct HTML for referring to an external style sheet? a- <link rel="stylesheet" type="text/css" href="mystyle.css"> b- <style src="mystyle.css" /> c- <stylesheet>mystyle.css</stylesheet /> d- None of the above 20- Which is the correct CSS syntax? a- body:color=black b- {body;color:black} c- {body:color=black(body} d- body {color: black} 21- Which CSS property controls the text size? a. font-size b. font-style c. text-style d. text-size 22- How do you add a background color for all <h1> elements? a- h1 {background-color:#ffffff} b- all.h1 {background-color:#ffffff} c- h1.all {background-color:#ffffff} d- None of the above 23- The Web where the companies use it as a platform to create collaborative, community-based sites such as social networking sites, blogs, wikis, etc. is: a. Web 1.0 b. Web 1.2 c. Web 2.0 d. Web The "s" character in the "Https" protocol stands for: a. Standard b. Smart c. Secured d. Strong 7

396 25- RIA stands for: a. Rich Internet Applications b. Right Internet Applications c. Rich Interconnection Applications d. Random Internal Applications 26- A specialized search engines that focus on specific topics are called: a. Location-based search b. Vertical search c. Search engine marketing d. Search engine optimization 27- The websites that allow users to edit existing content and add new information are called: a. Wikis b. Social networking c. Social media d. Social bookmarking 28- One of the following websites is not Social networking website: a. Youtube b. Facebook c. Twitter d. Second Life 29- One of the following websites is a Social bookmarking website: a. Youtube b. Delicious c. LinkedIn d. Second Life 30- The open source web browser is: a. Opera b. Firefox c. Explorer d. All of the above 8

397 1-(4 Marks) Q2: Write the code for ".css" file that gives the following output. (7 Marks) Color is red and size is 20pt Color is navy Color is tan Margin left 15px and size 11pt Color is green When you move the mouse over it the color is black When you visit the link it will be yellow When the link is active it will be blue 9

398 2-: (3 Marks) The table font is "Trebuchet MS". The header background color is #A7C942 and text color is white and font size is 18px The background color is #EAF2D3. Use the class name "alt" for the table row. The border size is1px and color is #98bf21 10

399 Q3: Build the following HTML form and write the Java Script code that shows the selected radio button value in a message box when you click on the "Display value" button. (7 Marks) 11

400 Q3: Build the following HTML form and write the Java Script code that shows the selected radio button value in a message box when you click on the "Display value" button. (7 Marks) 12

401 13

402 Q4: Write the Java Script code that reads an integer "n" via a prompt message and then prints a pyramid of stars on the screen with "n" length. (4 Marks) 14

Chapter 4 - Introduction to XHTML: Part 1

Chapter 4 - Introduction to XHTML: Part 1 Chapter 4 - Introduction to XHTML: Part 1 Outline 4.1 Introduction 4.2 Editing XHTML 4.3 First XHTML Example 4.4 W3C XHTML Validation Service 4.5 Headers 4.6 Linking 4.7 Images 4.8 Special Characters and

More information

Introduction to XHTML Pearson Education, Inc. All rights reserved.

Introduction to XHTML Pearson Education, Inc. All rights reserved. 1 4 Introduction to XHTML 2 To read between the lines was easier than to follow the text. Henry James High thoughts must have high language. Aristophanes Yea, from the table of my memory I ll wipe away

More information

Internet and New Media (INM)

Internet and New Media (INM) Internet and New Media (INM) Chapter 02 XHTML Victor M. Garcia-Barrios IICM @ TUGRAZ 1 2 Agenda Introduction Editing XHTML First XHTML Example W3C XHTML Validation Service Headings Linking Images Special

More information

IT350 Web and Internet Programming. XHTML Tables and Forms (from Chapter 4 of the text 4 th edition Chapter 2 of the text 5 th edition)

IT350 Web and Internet Programming. XHTML Tables and Forms (from Chapter 4 of the text 4 th edition Chapter 2 of the text 5 th edition) IT350 Web and Internet Programming XHTML Tables and Forms (from Chapter 4 of the text 4 th edition Chapter 2 of the text 5 th edition) 4.10 Tables 1 Table Basics table element border, summary, caption

More information

Chapter 4 - Introduction to XHTML: Part 1

Chapter 4 - Introduction to XHTML: Part 1 Chapter - Introduction to XHTML: Part 1.1 Introduction.2 Elements and Attributes.3 Editing XHTML. Common Elements.5 W3C XHTML Validation Service.6 Headers. Linking.8 Images.9 Special Characters and More

More information

History and Backgound: Internet & Web 2.0

History and Backgound: Internet & Web 2.0 1 History and Backgound: Internet & Web 2.0 History of the Internet and World Wide Web 2 ARPANET Implemented in late 1960 s by ARPA (Advanced Research Projects Agency of DOD) Networked computer systems

More information

CISC 1400 Discrete Structures

CISC 1400 Discrete Structures CISC 1400 Discrete Structures Building a Website 1 The Internet A "network of networks" that consists of millions of smaller domestic, academic, business, and government networks. Worldwide, publicly accessible

More information

IT350 Web & Internet Programming. Fall 2012

IT350 Web & Internet Programming. Fall 2012 IT350 Web & Internet Programming Fall 2012 Asst. Prof. Adina Crăiniceanu http://www.usna.edu/users/cs/adina/teaching/it350/fall2012/ 2 Outline Class Survey / Role Call What is: - the web/internet? - web

More information

Dive Into Web 2.0 (In Chapter 3) Part One

Dive Into Web 2.0 (In Chapter 3) Part One Internet & World Wide Web: How to Program by Deitel and Deitel Dive Into Web 2.0 (In Chapter 3) Part One 1 Some Interesting Quotes Network effects from user contributions are the key to market dominance

More information

Introduction to XHTML: Part 2

Introduction to XHTML: Part 2 L Introduction to XHTML: Part 2 Objectives To be able to create tables with rows and columns of data. To be able to control table formatting. To be able to create and use forms. To be able to create and

More information

Module 1: Internet Basics for Web Development (II)

Module 1: Internet Basics for Web Development (II) INTERNET & WEB APPLICATION DEVELOPMENT SWE 444 Fall Semester 2008-2009 (081) Module 1: Internet Basics for Web Development (II) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of

More information

Chapter 2: Introduction to HTML Part 1 HTML. Editing HTML. Editing HTML. HTML Concepts. Introduction to HTML: Part 1. CS 80: Internet Programming

Chapter 2: Introduction to HTML Part 1 HTML. Editing HTML. Editing HTML. HTML Concepts. Introduction to HTML: Part 1. CS 80: Internet Programming Chapter 2: Introduction to HTML Part 1 CS 80: Internet Programming Instructor: Mark Edmonds HTML What does it stand for? Hypertext markup language What is a markup language? Not a traditional programming

More information

CHAPTER 2 MARKUP LANGUAGES: XHTML 1.0

CHAPTER 2 MARKUP LANGUAGES: XHTML 1.0 WEB TECHNOLOGIES A COMPUTER SCIENCE PERSPECTIVE CHAPTER 2 MARKUP LANGUAGES: XHTML 1.0 Modified by Ahmed Sallam Based on original slides by Jeffrey C. Jackson reserved. 0-13-185603-0 HTML HELLO WORLD! Document

More information

Introduction to Computers and the Internet Pearson Education, Inc. All rights reserved.

Introduction to Computers and the Internet Pearson Education, Inc. All rights reserved. 1 1 Introduction to Computers and the Internet 2 The renaissance of interest in the web that we call Web 2.0 has reached the mainstream. Tim O Reilly Billions of queries stream across the servers of these

More information

HTML HTML. What is HTML? What is Markup? HTML Markup (Tags) Hypertext Markup Language

HTML HTML. What is HTML? What is Markup? HTML Markup (Tags) Hypertext Markup Language HTML IT Engineering I Instructor: Ali B. Hashemi What is HTML? Hypertext Markup Language Hypertext:Text with links to other documents A key technology for the Web A simple language for specifying document

More information

HTML. IT Engineering I Instructor: Ali B. Hashemi

HTML. IT Engineering I Instructor: Ali B. Hashemi HTML IT Engineering I Instructor: Ali B. Hashemi 1 1 What is HTML? Hypertext Markup Language Hypertext:Text with links to other documents A key technology for the Web A simple language for specifying document

More information

CSI 3140 WWW Structures, Techniques and Standards. Markup Languages: XHTML 1.0

CSI 3140 WWW Structures, Techniques and Standards. Markup Languages: XHTML 1.0 CSI 3140 WWW Structures, Techniques and Standards Markup Languages: XHTML 1.0 HTML Hello World! Document Type Declaration Document Instance Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C. Jackson

More information

A Brief Introduction to HTML

A Brief Introduction to HTML A P P E N D I X HTML SuMMAry J A Brief Introduction to HTML A web page is written in a language called HTML (Hypertext Markup Language). Like Java code, HTML code is made up of text that follows certain

More information

96 Intermediate HTML 4 Chapter 4

96 Intermediate HTML 4 Chapter 4 iw3htp_04.fm Page 96 Thursday, April 13, 2000 12:26 PM 96 Intermediate HTML 4 Chapter 4 4 Intermediate HTML 4 1 2 3 4 5 6 7 Internet

More information

Fundamentals of Information Systems, Seventh Edition

Fundamentals of Information Systems, Seventh Edition Fundamentals of Information Systems, Seventh Edition Chapter 4 Telecommunications, the Internet, Intranets, and Extranets Fundamentals of Information Systems, Seventh Edition 1 An Overview of Telecommunications

More information

Unit 4 The Web. Computer Concepts Unit Contents. 4 Web Overview. 4 Section A: Web Basics. 4 Evolution

Unit 4 The Web. Computer Concepts Unit Contents. 4 Web Overview. 4 Section A: Web Basics. 4 Evolution Unit 4 The Web Computer Concepts 2016 ENHANCED EDITION 4 Unit Contents Section A: Web Basics Section B: Browsers Section C: HTML Section D: HTTP Section E: Search Engines 2 4 Section A: Web Basics 4 Web

More information

Chapter 1 Introduction to HTML, XHTML, and CSS

Chapter 1 Introduction to HTML, XHTML, and CSS Chapter 1 Introduction to HTML, XHTML, and CSS MULTIPLE CHOICE 1. The world s largest network is. a. the Internet c. Newsnet b. the World Wide Web d. both A and B A PTS: 1 REF: HTML 2 2. ISPs utilize data

More information

Chapter 4. Introduction to XHTML: Part 1

Chapter 4. Introduction to XHTML: Part 1 Chapter 4. Introduction to XHTML: Part 1 XHTML is a markup language for identifying the elements of a page so a browser can render that page on a computer screen. Document presentation is generally separated

More information

HTML Summary. All of the following are containers. Structure. Italics Bold. Line Break. Horizontal Rule. Non-break (hard) space.

HTML Summary. All of the following are containers. Structure. Italics Bold. Line Break. Horizontal Rule. Non-break (hard) space. HTML Summary Structure All of the following are containers. Structure Contains the entire web page. Contains information

More information

Chapter 2 The Internet and World Wide Web

Chapter 2 The Internet and World Wide Web Chapter 2 The Internet and World Wide Web Chapter 2 Objectives Explain how to access and connect to the Internet Explain how to view pages and search for information on the Web Describe the types of Web

More information

The Internet, the Web, and Electronic Commerce The McGraw-Hill Companies, Inc. All rights reserved.

The Internet, the Web, and Electronic Commerce The McGraw-Hill Companies, Inc. All rights reserved. Discuss the origins of the Internet and the Web. Describe how to access the Web using providers and browsers. Discuss Internet communications, including e- mail, instant messaging, social networking, blogs,

More information

1/6/ :28 AM Approved New Course (First Version) CS 50A Course Outline as of Fall 2014

1/6/ :28 AM Approved New Course (First Version) CS 50A Course Outline as of Fall 2014 1/6/2019 12:28 AM Approved New Course (First Version) CS 50A Course Outline as of Fall 2014 CATALOG INFORMATION Dept and Nbr: CS 50A Title: WEB DEVELOPMENT 1 Full Title: Web Development 1 Last Reviewed:

More information

Tutorial 1 Getting Started with HTML5. HTML, CSS, and Dynamic HTML 5 TH EDITION

Tutorial 1 Getting Started with HTML5. HTML, CSS, and Dynamic HTML 5 TH EDITION Tutorial 1 Getting Started with HTML5 HTML, CSS, and Dynamic HTML 5 TH EDITION Objectives Explore the history of the Internet, the Web, and HTML Compare the different versions of HTML Study the syntax

More information

Internet Basics. Basic Terms and Concepts. Connecting to the Internet

Internet Basics. Basic Terms and Concepts. Connecting to the Internet Internet Basics In this Learning Unit, we are going to explore the fascinating and ever-changing world of the Internet. The Internet is the largest computer network in the world, connecting more than a

More information

A HTML document has two sections 1) HEAD section and 2) BODY section A HTML file is saved with.html or.htm extension

A HTML document has two sections 1) HEAD section and 2) BODY section A HTML file is saved with.html or.htm extension HTML Website is a collection of web pages on a particular topic, or of a organization, individual, etc. It is stored on a computer on Internet called Web Server, WWW stands for World Wide Web, also called

More information

Certified HTML Designer VS-1027

Certified HTML Designer VS-1027 VS-1027 Certification Code VS-1027 Certified HTML Designer Certified HTML Designer HTML Designer Certification allows organizations to easily develop website and other web based applications which are

More information

Chapter 1 Self Test. LATIHAN BAB 1. tjetjeprb{at}gmail{dot}com. webdesign/favorites.html :// / / / that houses that information. structure?

Chapter 1 Self Test. LATIHAN BAB 1. tjetjeprb{at}gmail{dot}com. webdesign/favorites.html :// / / / that houses that information. structure? LATIHAN BAB 1 Chapter 1 Self Test 1. What is a web browser? 2. What does HTML stand for? 3. Identify the various parts of the following URL: http://www.mcgrawhill.com/books/ webdesign/favorites.html ://

More information

Introduction to Web Technologies

Introduction to Web Technologies Introduction to Web Technologies James Curran and Tara Murphy 16th April, 2009 The Internet CGI Web services HTML and CSS 2 The Internet is a network of networks ˆ The Internet is the descendant of ARPANET

More information

Summary 4/5. (contains info about the html)

Summary 4/5. (contains info about the html) Summary Tag Info Version Attributes Comment 4/5

More information

Principles of Information Systems textbook: Principles of Information Systems, Sixth Edition. Dr.Amer Alzaidi Department of Information Systems

Principles of Information Systems textbook: Principles of Information Systems, Sixth Edition. Dr.Amer Alzaidi Department of Information Systems + Principles of Information Systems textbook: Principles of Information Systems, Sixth Edition Dr.Amer Alzaidi Department of Information Systems Chapter 4 Telecommunications, the Internet, Intranets, and

More information

Certified HTML5 Developer VS-1029

Certified HTML5 Developer VS-1029 VS-1029 Certified HTML5 Developer Certification Code VS-1029 HTML5 Developer Certification enables candidates to develop websites and web based applications which are having an increased demand in the

More information

Introduction to Computers and Visual Basic.Net Pearson Education, Inc. All rights reserved.

Introduction to Computers and Visual Basic.Net Pearson Education, Inc. All rights reserved. 1 1 Introduction to Computers and Visual Basic.Net 2 OBJECTIVES In this chapter you will learn: Basic computing concepts. The different types of programming languages. The evolution of the Basic Programming

More information

Web Publishing Basics I

Web Publishing Basics I Web Publishing Basics I Jeff Pankin Information Services and Technology Contents Course Objectives... 2 Creating a Web Page with HTML... 3 What is Dreamweaver?... 3 What is HTML?... 3 What are the basic

More information

Html basics Course Outline

Html basics Course Outline Html basics Course Outline Description Learn the essential skills you will need to create your web pages with HTML. Topics include: adding text any hyperlinks, images and backgrounds, lists, tables, and

More information

introduction to XHTML

introduction to XHTML introduction to XHTML XHTML stands for Extensible HyperText Markup Language and is based on HTML 4.0, incorporating XML. Due to this fusion the mark up language will remain compatible with existing browsers

More information

The Internet, the Web, and Electronic Commerce The McGraw-Hill Companies, Inc. All rights reserved.

The Internet, the Web, and Electronic Commerce The McGraw-Hill Companies, Inc. All rights reserved. Discuss the origins of the Internet and the Web. Describe how to access the Web using providers and browsers. Discuss Internet communications, including e- mail, instant messaging, social networking, blogs,

More information

Web Engineering (CC 552)

Web Engineering (CC 552) Web Engineering (CC 552) Introduction Dr. Mohamed Magdy mohamedmagdy@gmail.com Room 405 (CCIT) Course Goals n A general understanding of the fundamentals of the Internet programming n Knowledge and experience

More information

Web Design. Basic Concepts

Web Design. Basic Concepts Web Design Basic Concepts Web Design Web Design: Web design is the creation of a Web page using hypertext or hypermedia to be viewed on the World Wide Web. Web sites may be relatively simple, or highly

More information

Static Webpage Development

Static Webpage Development Dear Student, Based upon your enquiry we are pleased to send you the course curriculum for PHP Given below is the brief description for the course you are looking for: - Static Webpage Development Introduction

More information

A network is a group of two or more computers that are connected to share resources and information.

A network is a group of two or more computers that are connected to share resources and information. Chapter 1 Introduction to HTML, XHTML, and CSS HTML Hypertext Markup Language XHTML Extensible Hypertext Markup Language CSS Cascading Style Sheets The Internet is a worldwide collection of computers and

More information

1.264 Lecture 12. HTML Introduction to FrontPage

1.264 Lecture 12. HTML Introduction to FrontPage 1.264 Lecture 12 HTML Introduction to FrontPage HTML Subset of Structured Generalized Markup Language (SGML), a document description language SGML is ISO standard Current version of HTML is version 4.01

More information

HTML and CSS COURSE SYLLABUS

HTML and CSS COURSE SYLLABUS HTML and CSS COURSE SYLLABUS Overview: HTML and CSS go hand in hand for developing flexible, attractively and user friendly websites. HTML (Hyper Text Markup Language) is used to show content on the page

More information

Objectives. Introduction to HTML. Objectives. Objectives

Objectives. Introduction to HTML. Objectives. Objectives Objectives Introduction to HTML Developing a Basic Web Page Review the history of the Web, the Internet, and HTML. Describe different HTML standards and specifications. Learn about the basic syntax of

More information

Unit 5 Web Publishing Systems Page 1 of 13 Part 4 HTML Part 4

Unit 5 Web Publishing Systems Page 1 of 13 Part 4 HTML Part 4 Unit 5 Web Publishing Systems Page 1 of 13 Part 4 HTML 4.01 Version: 4.01 Transitional Hypertext Markup Language is the coding behind web publishing. In this tutorial, basic knowledge of HTML will be covered

More information

COMSC-030 Web Site Development- Part 1. Part-Time Instructor: Joenil Mistal

COMSC-030 Web Site Development- Part 1. Part-Time Instructor: Joenil Mistal COMSC-030 Web Site Development- Part 1 Part-Time Instructor: Joenil Mistal Chapter 1 1 HTML and Web Page Basics Are you interested in building your own Web pages? This chapter introduces you to basic HTML

More information

Using the Internet and the World Wide Web

Using the Internet and the World Wide Web Using the Internet and the World Wide Web Computer Literacy BASICS: A Comprehensive Guide to IC 3, 3 rd Edition 1 Objectives Understand the difference between the Internet and the World Wide Web. Identify

More information

HTML TAG SUMMARY HTML REFERENCE 18 TAG/ATTRIBUTE DESCRIPTION PAGE REFERENCES TAG/ATTRIBUTE DESCRIPTION PAGE REFERENCES MOST TAGS

HTML TAG SUMMARY HTML REFERENCE 18 TAG/ATTRIBUTE DESCRIPTION PAGE REFERENCES TAG/ATTRIBUTE DESCRIPTION PAGE REFERENCES MOST TAGS MOST TAGS CLASS Divides tags into groups for applying styles 202 ID Identifies a specific tag 201 STYLE Applies a style locally 200 TITLE Adds tool tips to elements 181 Identifies the HTML version

More information

Student, Perfect Midterm Exam March 24, 2006 Exam ID: 3193 CS-081/Vickery Page 1 of 5

Student, Perfect Midterm Exam March 24, 2006 Exam ID: 3193 CS-081/Vickery Page 1 of 5 Student, Perfect Midterm Exam March 24, 2006 Exam ID: 3193 CS-081/Vickery Page 1 of 5 NOTE: It is my policy to give a failing grade in the course to any student who either gives or receives aid on any

More information

2.1 Origins and Evolution of HTML

2.1 Origins and Evolution of HTML 2.1 Origins and Evolution of HTML - HTML was defined with SGML - Original intent of HTML: General layout of documents that could be displayed by a wide variety of computers - Recent versions: - HTML 4.0

More information

Part 3: Online Social Networks

Part 3: Online Social Networks 1 Part 3: Online Social Networks Today's plan Project 2 Questions? 2 Social networking services Social communities Bebo, MySpace, Facebook, etc. Content sharing YouTube, Flickr, MSN Soapbox, etc. Corporate

More information

HTML. HTML Evolution

HTML. HTML Evolution Overview stands for HyperText Markup Language. Structured text with explicit markup denoted within < and > delimiters. Not what-you-see-is-what-you-get (WYSIWYG) like MS word. Similar to other text markup

More information

Bridges To Computing

Bridges To Computing Bridges To Computing General Information: This document was created for use in the "Bridges to Computing" project of Brooklyn College. You are invited and encouraged to use this presentation to promote

More information

Web 2.0, AJAX and RIAs

Web 2.0, AJAX and RIAs Web 2.0, AJAX and RIAs Asynchronous JavaScript and XML Rich Internet Applications Markus Angermeier November, 2005 - some of the themes of Web 2.0, with example-sites and services Web 2.0 Common usage

More information

HTML, XHTML, and CSS. Sixth Edition. Chapter 1. Introduction to HTML, XHTML, and

HTML, XHTML, and CSS. Sixth Edition. Chapter 1. Introduction to HTML, XHTML, and HTML, XHTML, and CSS Sixth Edition Chapter 1 Introduction to HTML, XHTML, and CSS Chapter Objectives Describe the Internet and its associated key terms Describe the World Wide Web and its associated key

More information

Developing Ajax Web Apps with GWT. Session I

Developing Ajax Web Apps with GWT. Session I Developing Ajax Web Apps with GWT Session I Contents Introduction Traditional Web RIAs Emergence of Ajax Ajax ( GWT ) Google Web Toolkit Installing and Setting up GWT in Eclipse The Project Structure Running

More information

Discovering Computers Chapter 2 The Internet and World Wide Web

Discovering Computers Chapter 2 The Internet and World Wide Web Discovering Computers 2009 Chapter 2 The Internet and World Wide Web Chapter 2 Objectives Discuss the history of the Internet Describe the types of Web sites Explain how to access and connect to the Internet

More information

Grade 9 :The Internet and HTML Code Unit 1

Grade 9 :The Internet and HTML Code Unit 1 Internet Basic: The internet is a world-wide system of computer networks and computers. Each user makes use of an internet service provider (ISP). The ISP will set up a user account which will contain

More information

As we design and build out our HTML pages, there are some basics that we may follow for each page, site, and application.

As we design and build out our HTML pages, there are some basics that we may follow for each page, site, and application. Extra notes - Client-side Design and Development Dr Nick Hayward HTML - Basics A brief introduction to some of the basics of HTML. Contents Intro element add some metadata define a base address

More information

Web Development IB PRECISION EXAMS

Web Development IB PRECISION EXAMS PRECISION EXAMS Web Development IB EXAM INFORMATION Items 53 Points 73 Prerequisites COMPUTER TECHNOLOGY Grade Level 10-12 Course Length ONE YEAR Career Cluster INFORMATION TECHNOLOGY Performance Standards

More information

INTERNET PROGRAMMING INTRODUCTION

INTERNET PROGRAMMING INTRODUCTION INTERNET PROGRAMMING INTRODUCTION Software Engineering Branch / 4 th Class Computer Engineering Department University of Technology ORGANIZATION Lecture Mondays, 08:30-10:30 (Hall 4). Project 1. The project

More information

HTTP & Websites. Web Browsers. Web Servers vs. Web sites. World Wide Web. Internet Explorer. Surfing the World Wide Web. Part 4. The World Wide Web

HTTP & Websites. Web Browsers. Web Servers vs. Web sites. World Wide Web. Internet Explorer. Surfing the World Wide Web. Part 4. The World Wide Web HTTP & Websites Web Browsers Part 4 Surfing the World Wide Web World Wide Web Web Servers vs. Web sites The World Wide Web massive collection of websites on the Internet they link to each other and form

More information

Lecture : 3. Practical : 2. Course Credit. Tutorial : 0. Total : 5. Course Learning Outcomes

Lecture : 3. Practical : 2. Course Credit. Tutorial : 0. Total : 5. Course Learning Outcomes Course Title Course Code WEB DESIGNING TECHNOLOGIES DCE311 Lecture : 3 Course Credit Practical : Tutorial : 0 Total : 5 Course Learning Outcomes At end of the course, students will be able to: Understand

More information

HTML CS 4640 Programming Languages for Web Applications

HTML CS 4640 Programming Languages for Web Applications HTML CS 4640 Programming Languages for Web Applications 1 Anatomy of (Basic) Website Your content + HTML + CSS = Your website structure presentation A website is a way to present your content to the world,

More information

The Internet and World Wide Web. Chapter4

The Internet and World Wide Web. Chapter4 The Internet and World Wide Web Chapter4 ITBIS105 IS-IT-UOB 2016 The Internet What is the Internet? Worldwide collection of millions of computers networks that connects ITBIS105 IS-IT-UOB 2016 2 History

More information

HTML Overview. With an emphasis on XHTML

HTML Overview. With an emphasis on XHTML HTML Overview With an emphasis on XHTML What is HTML? Stands for HyperText Markup Language A client-side technology (i.e. runs on a user s computer) HTML has a specific set of tags that allow: the structure

More information

Programmazione Web a.a. 2017/2018 HTML5

Programmazione Web a.a. 2017/2018 HTML5 Programmazione Web a.a. 2017/2018 HTML5 PhD Ing.Antonino Raucea antonino.raucea@dieei.unict.it 1 Introduzione HTML HTML is the standard markup language for creating Web pages. HTML stands for Hyper Text

More information

NEW WEBMASTER HTML & CSS FOR BEGINNERS COURSE SYNOPSIS

NEW WEBMASTER HTML & CSS FOR BEGINNERS COURSE SYNOPSIS NEW WEBMASTER HTML & CSS FOR BEGINNERS COURSE SYNOPSIS LESSON 1 GETTING STARTED Before We Get Started; Pre requisites; The Notepad++ Text Editor; Download Chrome, Firefox, Opera, & Safari Browsers; The

More information

Internet. Class-In charge: S.Sasirekha

Internet. Class-In charge: S.Sasirekha Internet Class-In charge: S.Sasirekha COMPUTER NETWORK A computer network is a collection of two or more computers, which are connected together to share information and resources. Network Operating Systems

More information

Chapter 4 A Hypertext Markup Language Primer

Chapter 4 A Hypertext Markup Language Primer Chapter 4 A Hypertext Markup Language Primer XHTML Mark Up with Tags Extensible Hypertext Markup Language Format Word/abbreviation in < > PAIR Singleton (not surround text) />

More information

Chapter 2 The Internet and World Wide Web

Chapter 2 The Internet and World Wide Web Chapter 2 The Internet and World Wide Web Chapter 2 Objectives Discuss the history of the Internet Describe the types of Web sites Explain how to access and connect to the Internet Recognize how Web pages

More information

History of the Internet. The Internet - A Huge Virtual Network. Global Information Infrastructure. Client Server Network Connectivity

History of the Internet. The Internet - A Huge Virtual Network. Global Information Infrastructure. Client Server Network Connectivity History of the Internet It is desired to have a single network Interconnect LANs using WAN Technology Access any computer on a LAN remotely via WAN technology Department of Defense sponsors research ARPA

More information

UFCEKG Lecture 2. Mashups N. H. N. D. de Silva (Slides adapted from Prakash Chatterjee, UWE)

UFCEKG Lecture 2. Mashups N. H. N. D. de Silva (Slides adapted from Prakash Chatterjee, UWE) UFCEKG 20 2 Data, Schemas & Applications Lecture 2 Introduction to thewww WWW, URLs, HTTP, Services and Mashups N. H. N. D. de Silva (Slides adapted from Prakash Chatterjee, UWE) Suppose all the information

More information

What is a web site? Web editors Introduction to HTML (Hyper Text Markup Language)

What is a web site? Web editors Introduction to HTML (Hyper Text Markup Language) What is a web site? Web editors Introduction to HTML (Hyper Text Markup Language) What is a website? A website is a collection of web pages containing text and other information, such as images, sound

More information

COPYRIGHTED MATERIAL. Contents. Chapter 1: Creating Structured Documents 1

COPYRIGHTED MATERIAL. Contents. Chapter 1: Creating Structured Documents 1 59313ftoc.qxd:WroxPro 3/22/08 2:31 PM Page xi Introduction xxiii Chapter 1: Creating Structured Documents 1 A Web of Structured Documents 1 Introducing XHTML 2 Core Elements and Attributes 9 The

More information

INTRODUCTION TO HTML5! HTML5 Page Structure!

INTRODUCTION TO HTML5! HTML5 Page Structure! INTRODUCTION TO HTML5! HTML5 Page Structure! What is HTML5? HTML5 will be the new standard for HTML, XHTML, and the HTML DOM. The previous version of HTML came in 1999. The web has changed a lot since

More information

Chapter 3. E-commerce The Evolution of the Internet 1961 Present. The Internet: Technology Background. The Internet: Key Technology Concepts

Chapter 3. E-commerce The Evolution of the Internet 1961 Present. The Internet: Technology Background. The Internet: Key Technology Concepts E-commerce 2015 business. technology. society. eleventh edition Kenneth C. Laudon Carol Guercio Traver Chapter 3 E-commerce Infrastructure: The Internet, Web, and Mobile Platform Copyright 2015 Pearson

More information

WEBINAR. Web Browsing 101 1/12/2012 WEBINAR TIPS:

WEBINAR. Web Browsing 101 1/12/2012 WEBINAR TIPS: Browsing 101 WEBINAR TIPS: 1. Power off cell phones. 2. If accessing webinar through telephone, turn down volume of computer speakers (or mute them.) 3. Conference attendees will be muted during webinar

More information

Hyper Text Markup Language HTML: A Tutorial

Hyper Text Markup Language HTML: A Tutorial Hyper Text Markup Language HTML: A Tutorial Ahmed Othman Eltahawey December 21, 2016 The World Wide Web (WWW) is an information space where documents and other web resources are located. Web is identified

More information

Module 2-1-1: Markup Languages & HTML

Module 2-1-1: Markup Languages & HTML WEB ENGINEERING G & DEVELOPMENT SWE 363 Spring Semester 2008-2009 (082) Module 2-1-1: Markup Languages & HTML Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals

More information

CSC 121 Computers and Scientific Thinking

CSC 121 Computers and Scientific Thinking CSC 121 Computers and Scientific Thinking Fall 2005 HTML and Web Pages 1 HTML & Web Pages recall: a Web page is a text document that contains additional formatting information in the HyperText Markup Language

More information

11. HTML5 and Future Web Application

11. HTML5 and Future Web Application 11. HTML5 and Future Web Application 1. Where to learn? http://www.w3schools.com/html/html5_intro.asp 2. Where to start: http://www.w3schools.com/html/html_intro.asp 3. easy to start with an example code

More information

Tennessee. Trade & Industrial Course Web Page Design II - Site Designer Standards. A Guide to Web Development Using Adobe Dreamweaver CS3 2009

Tennessee. Trade & Industrial Course Web Page Design II - Site Designer Standards. A Guide to Web Development Using Adobe Dreamweaver CS3 2009 Tennessee Trade & Industrial Course 655745 Web Page Design II - Site Designer Standards A Guide to Web Development Using Adobe Dreamweaver CS3 2009 ation Key SE Student Edition LE Learning Expectation

More information

A Balanced Introduction to Computer Science, 3/E

A Balanced Introduction to Computer Science, 3/E A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University 2011 Pearson Prentice Hall ISBN 978-0-13-216675-1 Chapter 2 HTML and Web Pages 1 HTML & Web Pages recall: a Web page is

More information

By Ryan Stevenson. Guidebook #2 HTML

By Ryan Stevenson. Guidebook #2 HTML By Ryan Stevenson Guidebook #2 HTML Table of Contents 1. HTML Terminology & Links 2. HTML Image Tags 3. HTML Lists 4. Text Styling 5. Inline & Block Elements 6. HTML Tables 7. HTML Forms HTML Terminology

More information

OU EDUCATE TRAINING MANUAL

OU EDUCATE TRAINING MANUAL OU EDUCATE TRAINING MANUAL OmniUpdate Web Content Management System El Camino College Staff Development 310-660-3868 Course Topics: Section 1: OU Educate Overview and Login Section 2: The OmniUpdate Interface

More information

Chapter 1 Getting Started with HTML 5 1. Chapter 2 Introduction to New Elements in HTML 5 21

Chapter 1 Getting Started with HTML 5 1. Chapter 2 Introduction to New Elements in HTML 5 21 Table of Contents Chapter 1 Getting Started with HTML 5 1 Introduction to HTML 5... 2 New API... 2 New Structure... 3 New Markup Elements and Attributes... 3 New Form Elements and Attributes... 4 Geolocation...

More information

Announcements. Paper due this Wednesday

Announcements. Paper due this Wednesday Announcements Paper due this Wednesday 1 Client and Server Client and server are two terms frequently used Client/Server Model Client/Server model when talking about software Client/Server model when talking

More information

Web Design 101. What is HTML? HTML Tags. Web Browsers. <!DOCTYPE html> <html> <body> <h1>my First Heading</h1> <p>my first paragraph.

Web Design 101. What is HTML? HTML Tags. Web Browsers. <!DOCTYPE html> <html> <body> <h1>my First Heading</h1> <p>my first paragraph. What is HTML? Web Design 101 HTML is a language for describing web pages. HTML stands for Hyper Text Markup Language HTML is a markup language à A markup language is a set of markup tags The tags describe

More information

Agenda. INTRODUCTION TO WEB DEVELOPMENT AND HTML <Lecture 1> 1/20/2013. What is a Web Developer? Rommel Anthony Palomino Spring

Agenda. INTRODUCTION TO WEB DEVELOPMENT AND HTML <Lecture 1> 1/20/2013. What is a Web Developer? Rommel Anthony Palomino Spring INTRODUCTION TO WEB DEVELOPMENT AND Rommel Anthony Palomino Spring 2013 2 What is a Web Developer? Agenda History of the Internet Web 2.0 What is web development today Technology part of it

More information

ICT IGCSE Practical Revision Presentation Web Authoring

ICT IGCSE Practical Revision Presentation Web Authoring 21.1 Web Development Layers 21.2 Create a Web Page Chapter 21: 21.3 Use Stylesheets 21.4 Test and Publish a Website Web Development Layers Presentation Layer Content layer: Behaviour layer Chapter 21:

More information

Index. CSS directive, # (octothorpe), intrapage links, 26

Index. CSS directive, # (octothorpe), intrapage links, 26 Holzschlag_.qxd 3/30/05 9:23 AM Page 299 Symbols @import CSS directive, 114-115 # (octothorpe), intrapage links, 26 A a element, 23, 163, 228 abbr element, 228 absolute keywords for font sizing, 144 absolute

More information

Islamic University of Gaza Faculty of Engineering Department of Computer Engineering ECOM Advanced Internet Technology Lab.

Islamic University of Gaza Faculty of Engineering Department of Computer Engineering ECOM Advanced Internet Technology Lab. Islamic University of Gaza Faculty of Engineering Department of Computer Engineering ECOM 5049 Advanced Internet Technology Lab Lab # 1 Eng. Haneen El-masry February, 2015 Objective To be familiar with

More information

Tennessee. Business Technology Course Code Web Design Essentials. HTML Essentials, Second Edition 2010

Tennessee. Business Technology Course Code Web Design Essentials. HTML Essentials, Second Edition 2010 Tennessee Business Technology Course Code 6501240 Web Design Essentials HTML Essentials, Second Edition 2010 Notation Key SE Student Edition LE Learning Expectation Standard 1.0 Demonstrate knowledge of

More information

ADOBE Dreamweaver CS3 Basics

ADOBE Dreamweaver CS3 Basics ADOBE Dreamweaver CS3 Basics IT Center Training Email: training@health.ufl.edu Web Page: http://training.health.ufl.edu This page intentionally left blank 2 8/16/2011 Contents Before you start with Dreamweaver....

More information

CSC Web Technologies, Spring HTML Review

CSC Web Technologies, Spring HTML Review CSC 342 - Web Technologies, Spring 2017 HTML Review HTML elements content : is an opening tag : is a closing tag element: is the name of the element attribute:

More information