, , and . The element defines an HTML form and contains these form elements. Common input types include text, radio buttons, checkboxes, and submit buttons. Forms submit data to a server using the GET or POST methods. Key attributes include action to specify the submission URL and name to identify form elements. HTML5 added new elements like , , and . Scripting languages allow dynamic interactions and processing of form data on the client-side or server-side.">, , and . The element defines an HTML form and contains these form elements. Common input types include text, radio buttons, checkboxes, and submit buttons. Forms submit data to a server using the GET or POST methods. Key attributes include action to specify the submission URL and name to identify form elements. HTML5 added new elements like , , and . Scripting languages allow dynamic interactions and processing of form data on the client-side or server-side."> Address: [go: up one dir, main page] Include Form Remove Scripts Session Cookies Open navigation menuClose suggestionsSearchSearchenChange LanguageUploadSign inSign inDownload free for days0 ratings0% found this document useful (0 votes)271 views85 pagesWeb Programming Unit-1 NotesHTML forms are used to collect user input through elements like <input>, <select>, and <textarea>. The <form> element defines an HTML form and contains these form elements. Common input types include text, radio buttons, checkboxes, and submit buttons. Forms submit data to a server using the GET or POST methods. Key attributes include action to specify the submission URL and name to identify form elements. HTML5 added new elements like <datalist>, <keygen>, and <output>. Scripting languages allow dynamic interactions and processing of form data on the client-side or server-side.Uploaded byKadasi AbishekAI-enhanced descriptionCopyright© © All Rights ReservedWe take content rights seriously. If you suspect this is your content, claim it here.Available FormatsDownload as PDF, TXT or read online on ScribdDownload nowDownloadSave Web Programming Unit-1 Notes For LaterDownloadSaveSave Web Programming Unit-1 Notes For Later0%0% found this document useful, undefined0%, undefinedEmbedSharePrintReport0 ratings0% found this document useful (0 votes)271 views85 pagesWeb Programming Unit-1 NotesHTML forms are used to collect user input through elements like <input>, <select>, and <textarea>. The <form> element defines an HTML form and contains these form elements. Common input types include text, radio buttons, checkboxes, and submit buttons. Forms submit data to a server using the GET or POST methods. Key attributes include action to specify the submission URL and name to identify form elements. HTML5 added new elements like <datalist>, <keygen>, and <output>. Scripting languages allow dynamic interactions and processing of form data on the client-side or server-side.Uploaded byKadasi AbishekAI-enhanced descriptionCopyright© © All Rights ReservedWe take content rights seriously. If you suspect this is your content, claim it here.Available FormatsDownload as PDF, TXT or read online on ScribdDownload nowDownloadSave Web Programming Unit-1 Notes For LaterCarousel PreviousCarousel NextDownloadSaveSave Web Programming Unit-1 Notes For Later0%0% found this document useful, undefined0%, undefinedEmbedSharePrintReportDownload nowDownloadYou are on page 1/ 85SearchFullscreenHTML FORMS:The <form> ElementHTML forms are used to collect user input.The <form> element defines an HTML form: <form> . form elements . </form>HTML forms contain form elements.Form elements are different types of input elements, checkboxes, radio buttons, submit buttons, andmore.The <input> ElementThe <input> element is the most important form element.The <input> element has many variations, depending on the type attribute.Here are the types used in this chapter:Type Descriptiontext Defines normal text inputradio Defines radio button input (for selecting one of many choices)submit Defines a submit button (for submitting the form)Text Input<input type="text"> defines a one-line input field for text inputRadio Button Input<input type="radio"> defines a radio button.Radio buttons let a user select ONE of a limited number of choicesThe Submit Button<input type="submit"> defines a button for submitting a form to a form-handler.The form-handler is typically a server page with a script for processing input data.The form-handler is specified in the form's action attributeThe Action AttributeThe action attribute defines the action to be performed when the form is submitted.The common way to submit a form to a server, is by using a submit button.Normally, the form is submitted to a web page on a web server.In the example above, a server-side script is specified to handle the submitted form:<form action="action_page.php">If the action attribute is omitted, the action is set to the current page.The Method AttributeThe method attribute specifies the HTTP method (GET or POST) to be used when submitting theforms:<form action="action_page.php" method="GET">or:<form action="action_page.php" method="POST"> When to Use GET?If the form submission is passive (like a search engine query), and without sensitive information.When you use GET, the form data will be visible in the page address:action_page.php?firstname=Mickey&lastname=Mouse When to Use POST?If the form is updating data, or includes sensitive information (password).POST offers better security because the submitted data is not visible in the page address.The Name AttributeTo be submitted correctly, each input field must have a name attribute.Grouping Form Data with <fieldset>The <fieldset> element groups related data in a form.The <legend> element defines a caption for the <fieldset> element.HTML Form AttributesAn HTML <form> element, with all possible attributes set, will look like this:<form action="action_page.php" method="GET" target="_blank" accept-charset="UTF-8"enctype="application/x-www-form-urlencoded" autocomplete="off" novalidate>.form elements.</form>Here is the list of <form> attributes:Attribute Descriptionaccept-charset Specifies the charset used in the submitted form (default: the page charset).action Specifies an address (url) where to submit the form (default: the submitting page).autocomplete Specifies if the browser should autocomplete the form (default: on).enctype Specifies the encoding of the submitted data (default: is url-encoded).method Specifies the HTTP method used when submitting the form (default: GET).name Specifies a name used to identify the form (for DOM usage: document.forms.name).novalidate Specifies that the browser should not validate the form.target Specifies the target of the address in the action attribute (default: _self).HTML FORM ELEMENTSThe <input> ElementThe most important form element is the <input> element.The <input> element can vary in many ways, depending on the type attribute.The <select> Element (Drop-Down List)The <select> element defines a drop-down list:Example<select name="cars"><option value="volvo">Volvo</option><option value="saab">Saab</option><option value="fiat">Fiat</option><option value="audi">Audi</option></select>The <option> elements defines the options to select.The list will normally show the first item as selected.You can add a selected attribute to define a predefined option.Example<option value="fiat" selected>Fiat</option>The <textarea> ElementThe <textarea> element defines a multi-line input field (a text area):The <button> ElementThe <button> element defines a clickable button:Example<button type="button" onclick="alert('Hello World!')">Click Me!</button>HTML5 Form ElementsHTML5 added the following form elements: <datalist> <keygen> <output>HTML5 <datalist> ElementThe <datalist> element specifies a list of pre-defined options for an <input> element.Users will see a drop-down list of pre-defined options as they input data.The list attribute of the <input> element, must refer to the id attribute of the <datalist> element.HTML5 <keygen> ElementThe purpose of the <keygen> element is to provide a secure way to authenticate users.The <keygen> element specifies a key-pair generator field in a form.When the form is submitted, two keys are generated, one private and one public.The private key is stored locally, and the public key is sent to the server.The public key could be used to generate a client certificate to authenticate the user in the future.HTML5 <output> ElementThe <output> element represents the result of a calculation (like one performed by a script).HTML Form ElementsTag Description<form> Defines an HTML form for user input<input> Defines an input control<textarea> Defines a multiline input control (text area)<label> Defines a label for an <input> element <fieldset> Groups related elements in a form <legend> Defines a caption for a <fieldset> element <select> Defines a drop-down list <optgroup> Defines a group of related options in a drop-down list <option> Defines an option in a drop-down list <button> Defines a clickable button <datalist> Specifies a list of pre-defined options for input controls <keygen> Defines a key-pair generator field (for forms) <output> Defines the result of a calculation HTML Frameset: The <frameset> tag is not supported in HTML5. The <frameset> tag defines a frameset. The <frameset> element holds one or more <frame> elements. Each <frame> element can hold a separate document. The <frameset> element specifies HOW MANY columns or rows there will be in the frameset, and HOW MUCH percentage/pixels of space will occupy each of them. Example A simple three-framed page: <frameset cols="25%,*,25%"> <frame src="frame_a.htm"> <frame src="frame_b.htm"> <frame src="frame_c.htm"> </frameset>SCRIPTING BASICS A scripting language is a form of programming language that is usually interpreted rather than compiled. Conventional programs are converted permanently into executable files before they are run. In contrast, programs in scripting language are interpreted one command at a time. Scripting languages are often written to facilitate enhanced features of Web sites. These features are processed on the server but the script in a specific page runs on the user's browser.In most cases, it is easier to write the code in a scripting language than in a compiled language.However, scripting languages are slower because the instructions are not handled solely by the basicinstruction processor.Scripting languages allow rapid development and can communicate easily with programs written inother languages.Scripting languages can be used to create specialized GUIs (graphical user interfaces) and forms thatenhance the convenience of search engines, Web-based e-mail and e-commerce.Many Web sites require that the user's browser be set to run scripts to take advantage of all thefeatures of the site. In some cases, Web sites are practically useless unless the user's computer is setto run programs locally in a scripting language.Client-side Scripting Environment (Browsers and Editors)The World Wide Web (WWW) began as a text-only medium-the first browsers didn't even supportimages within web pages.Today's websites can include a lot of features: graphics, sounds, animation, video, and occasionallyuseful content.Web scripting languages also known as client-side scripting languages, such as JavaScript, are one ofthe easiest ways to add dynamic state to a web page and to interact with users in new ways.HTML is a simple text markup language, it can't respond to the user, make decisions, or automaterepetitive tasks. Interactive tasks such as these require a more sophisticated language: a programminglanguage, or a scripting language.Although many programming languages are complex, scripting languages are generally simple. Theyhave a simple syntax, can perform tasks with a minimum of commands, and are easy to learn. Webscripting languages enable you to combine scripting with HTML to create interactive web pages.Scripts and ProgramsA movie or a play follows a script-a list of actions (or lines) for the actors to perform. A web scriptprovides the same type of instructions for the web browser. A script can range from a single line to afull-scale application. (In either case, Scripts usually run within a browser.)Some programming languages must be compiled, or translated, into machine code before they can beexecuted. Client-side scripts, on the other hand, are an interpreted language: The browser executeseach line of script as it comes to it.There is one main advantage to interpreted languages: Writing or changing a script is very simple.Changing a client-side script is as easy as changing a typical HTML document, and the change isexecuted as soon as you refresh the document in the browser.Characteristics of Interpreted LanguagesOne of the main benefits of interpreted languages is that they require no compilation.The language is interpreted at run-time so the instructions are executed immediately.Any errors in an interpreted program will result in the execution of the code to be halted.Interpreted languages also have a simple syntax which, for the user: makes them easy to learn and use assumes minimum programming knowledge or experience allows complex tasks to be performed in relatively few steps allows simple creation and editing in a variety of text editors allows the addition of dynamic and interactive activities to web pagesAlso, interpreted languages are generally portable across various hardware and network platforms andscripts can be embedded in standard text documents for added functionality.Unlike a compiler, an interpreter checks syntax and generates object code one source line at a time.Think of this as very similar to a group of translators at a United Nations' Conference, who each haveto convert sentences spoken by delegates into the native language of their representative.When an error is encountered, the interpreter immediately feeds back information on the type of errorand stops interpreting the code. This allows the programmer to see instantly the nature of the errorand where it has occurred. He or she can then make the necessary changes to the source code andhave it re-interpreted.As the interpreter executes each line of code at a time the programmer is able to see the results oftheir programs immediately which can also help with debugging.Advantages and Disadvantages of Interpreted LanguagesAdvantages easy to learn and use minimum programming knowledge or experience allows complex tasks to be performed in relatively few steps allows simple creation and editing in a variety of text editors allows the addition of dynamic and interactive activities to web pages edit and running of code is fast.Disadvantages usually run quite slowly limited access to low level and speed optimization code. limited commands to run detailed operations on graphics.Differences between Client-side and Server-side ScriptingClient-side EnvironmentThe client-side environment used to run scripts is usually a browser. The processing takes place onthe end users computer. The source code is transferred from the web server to the users computerover the internet and run directly in the browser.The scripting language needs to be enabled on the client computer. Sometimes if a user is consciousof security risks they may switch the scripting facility off. When this is the case a message usuallypops up to alert the user when script is attempting to run.Server-side EnvironmentThe server-side environment that runs a scripting language is a web server. A user's request isfulfilled by running a script directly on the web server to generate dynamic HTML pages. ThisHTML is then sent to the client browser. It is usually used to provide interactive web sites thatinterface to databases or other data stores on the server.This is different from client-side scripting where scripts are run by the viewing web browser, usuallyin JavaScript. The primary advantage to server-side scripting is the ability to highly customize theresponse based on the user's requirements, access rights, or queries into data stores.Types of scripting languagesSpecialised scripting languages include:Perl (Practical Extraction and Report Language). This is a popular string processing language forwriting small scripts for system administrators and web site maintainers. Much web development isnow done using Perl.Hypertalk is another example. It is the underlying scripting language of HyperCard.Lingo is the scripting language of Macromedia Director, an authoring system for develop high-performance multimedia content and applications for CDs, DVDs and the Internet.AppleScript, a scripting language for the Macintosh allows the user to send commands to theoperating system to, for example open applications, carry out complex data operations.JavaScript, perhaps the most publicised and well-known scripting language was initially developedby Netscape as LiveScript to allow more functionality and enhancement to web page authoring thatraw HTML could not accommodate. A standard version of JavaScript was later developed to work inboth Netscape and Microsoft's Internet Explorer, thus making the language to a large extent,universal. This means that JavaScript code can run on any platform that has a JavaScript interpreter.VBScript, a cut-down version of Visual Basic, used to enhance the features of web pages in InternetExplorer.INTRODUCING JAVASCRIPTJavaScript was developed by Netscape Communications Corporation, the maker of the Netscape webbrowser. JavaScript was the first web scripting language to be supported by browsers, and it is still byfar the most popular.JavaScript was originally called LiveScript and was first introduced in Netscape Navigator 2.0 in1995. Netscape Navigator was an early browser that held a large share of the browser market. It wassoon renamed JavaScript to indicate a marketing relationship with Sun's Java language.JavaScript is almost as easy to learn as HTML, and it can be included directly in HTML documents.What can you do with Javascript? Display messages to the user as part of a web page, in the browser's status line, or in alert boxes. Validate the contents of a form and make calculations (for example, an order form can automatically display a running total as you enter item quantities). Animate images or create images that change when you move the mouse over them. Create ad banners that interact with the user, rather than simply displaying a graphic. Detect the browser in use or its features and perform advanced functions only on browsers that support them. Detect installed plug-ins and notify the user if a plug-in is required. Modify all or part of a web page without requiring the user to reload it. Display or interact with data retrieved from a remote server.JavaScript Browser SupportAll the modern browsers come with built-in support for JavaScript. Frequently, you may need toenable or disable this support manually. The procedure of enabling and disabling JavaScript supportin your browsers: Internet Explorer, Firefox, chrome, and Opera are listed below.JavaScript in Internet ExplorerHere are simple steps to turn on or turn off JavaScript in your Internet Explorer − Follow Tools → Internet Options from the menu. Select Security tab from the dialog box. Click the Custom Level button. Scroll down till you find Scripting option. Select Enable radio button under Active scripting. Finally click OK and come outTo disable JavaScript support in your Internet Explorer, you need to select Disable radio button underActive scripting.JavaScript in FirefoxHere are the steps to turn on or turn off JavaScript in Firefox − Open a new tab → type about: config in the address bar. Then you will find the warning dialog. Select I’ll be careful, I promise! Then you will find the list of configure options in the browser. In the search bar, type javascript.enabled. There you will find the option to enable or disable javascript by right-clicking on the value of that option → select toggle.If javascript.enabled is true; it converts to false upon clicking toogle. If javascript is disabled; it getsenabled upon clicking toggle.JavaScript in ChromeHere are the steps to turn on or turn off JavaScript in Chrome − Click the Chrome menu at the top right hand corner of your browser. Select Settings. Click Show advanced settings at the end of the page. Under the Privacy section, click the Content settings button. In the "Javascript" section, select "Do not allow any site to run JavaScript" or "Allow all sites to run JavaScript (recommended)".JavaScript in OperaHere are the steps to turn on or turn off JavaScript in Opera − Follow Tools → Preferences from the menu. Select Advanced option from the dialog box. Select Content from the listed items. Select Enable JavaScript checkbox. Finally click OK and come out.To disable JavaScript support in your Opera, you should not select the Enable JavaScript checkbox.Warning for Non-JavaScript BrowsersIf you have to do something important using JavaScript, then you can display a warning message tothe user using <noscript> tags.You can add a noscript block immediately after the script block as follows −<html> <body> <script language="javascript" type="text/javascript"> <!-- document.write("Hello World!") //--> </script> <noscript> Sorry...JavaScript is needed to go ahead. </noscript> </body></html>Now, if the user's browser does not support JavaScript or JavaScript is not enabled, then the messagefrom </noscript> will be displayed on the screen.Where to put Javascript?JavaScript can be put in the <head> or in the <body> of an HTML document JavaScript functions should be defined in the <head>. This ensures that the function is loaded before it is needed JavaScript in the <body> will be executed as the page loadsJavaScript can be put in a separate .js file <script src="myJavaScriptFile.js"></script>Put this HTML wherever you would put the actual JavaScript codeAn external .js file lets you use the same JavaScript on multiple HTML pagesThe external .js file cannot itself contain a <script> tagJavaScript can be put in HTML form object, such as a buttonThis JavaScript will be executed when the form object is usedJavaScript ProgramsA computer program is a list of "instructions" to be "executed" by the computer.In a programming language, these program instructions are called statements.JavaScript is a programming language.JavaScript statements are separated by semicolons.<!DOCTYPE html><html><body><h1>JavaScript Statements</h1><p>Statements are separated by semicolons.</p><p>The variables x, y, and z are assigned the values 5, 6, and 11:</p><p id="demo"></p><script>var x = 5;var y = 6;var z = x + y;document.getElementById("demo").innerHTML = z;</script></body></html>JAVASCRIPT STATEMENTSJavaScript statements are composed of:Values, Operators, Expressions, Keywords, and Comments.JavaScript ValuesThe JavaScript syntax defines two types of values: Fixed values and variable values.Fixed values are called literals. Variable values are called variables.JavaScript Literals Array literals Boolean literals Floating-point literals Integers Object literals String literalsJavaScript : Array literalsIn Javascript an array literal is a list of expressions, each of which represents an array element,enclosed in a pair of square brackets ' [ ] ' . When an array is created using an array literal, it isinitialized with the specified values as its elements, and its length is set to the number of argumentsspecified. If no value is supplied it creates an empty array with zero length.Creating an empty array :var fruits = [ ];Creating an array with four elements.var fruits = ["Orange", "Apple", "Banana", "Mango"]Comma in array literalsThere is no need to specify all elements in an array literal. If we put two commas in a row at anyposition in an array then an unspecified element will be created in that place.The following example creates the fruits array :fruits = ["Orange", , "Mango"]This array has one empty element in the middle and two elements with values. ( fruits[0] is "Orange",fruits[1] is set to undefined, and fruits[2] is "Mango").If you include a single comma at the end of the elements, the comma is ignored. In the followingexample, the length of the array is three. There is no fruits[2].fruits = ["Orange", "Mango",]In the following example, the length of the array is four, and fruits[0] and fruits[2] are undefined.fruits = [ , 'Apple', , 'Orange'];JavaScript : Integers literalsAn integer must have at least one digit (0-9). No comma or blanks are allowed within an integer. It does not contain any fractional part. It can be either positive or negative, if no sign precedes it is assumed to be positive.In JavaScript, integers can be expressed in three different bases.1. Decimal ( base 10)Decimal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and there will be no leadingzeros.Example : 123, -20, 123452. Hexadecimal ( base 16)Hexadecimal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and letters A, B, C, D, E,F or a, b, c, d, e, f. A leading 0x or 0X indicates the number is hexadecimal.Example : 7b, -14, 30393. Octal (base 8)Octal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7. A leading 0 indicates the number isoctal.Example : 173, -24, 30071JavaScript : Floating number literalsA floating number has the following parts. A decimal integer. A decimal point ('.'). A fraction. An exponent.The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or "-").Example of some floating numbers : 8.2935 -14.72 12.4e3 [ Equivalent to 12.4 x 103 ] 4E-3 [ Equivalent to 4 x 10-3 => .004 ]JavaScript : Boolean literalsThe Boolean type has two literal values : true falseJavaScript : Object literalsAn object literal is zero or more pairs of comma separated list of property names and associatedvalues, enclosed by a pair of curly braces.In JavaScript an object literal is declared as follows:1. An object literal without properties:var userObject = {}2. An object literal with a few properties :var student = {First-name : "Suresy",Last-name : "Rayy",Roll-No : 12};Syntax RulesObject literals maintain the following syntax rules: There is a colon (:) between property name and value. A comma separates each property name/value from the next. There will be no comma after the last property name/value pair.JavaScript : String literalsJavaScript has its own way to deal with string literals. A string literal is zero or more characters,either enclosed in single quotation (') marks or double quotation (") marks. You can also use +operator to join strings. The following are the examples of string literals : string1 = "w3resource.com" string1 = 'w3resource.com' string1 = "1000" string1 = "google" + ".com"In addition to ordinary characters, you can include special characters in strings, as shown in thefollowing table.string1 = "First line. \n Second line."List of special characters used in JavaScript string :Character Meaning\b Backspace\f Form feed\n New line\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.\t Tab\' Single quote\" Double quote\\ Backslash character (\) The character with the Latin-1 encoding specified by up to three octal digits\XXX XXX between 0 and 377. For example, \100 is the octal sequence for the @ symbol. The character with the Latin-1 encoding specified by the two hexadecimal\xXX digits XX between 00 and FF. For example, \x40 is the hexadecimal sequence for the @ symbol. The Unicode character specified by the four hexadecimal digits XXXX. For\uXXXX example, \u0040 is the Unicode sequence for the @ symbol.The most important rules for writing fixed values are:Numbers are written with or without decimals:10.501001Strings are text, written within double or single quotes:"John Doe"'John Doe'Expressions can also represent fixed values:5+65 * 10JAVASCRIPT VARIABLESIn a programming language, variables are used to store data values.JavaScript uses the var keyword to define variables.An equal sign is used to assign values to variables.In this example, x is defined as a variable. Then, x is assigned (given) the value 6:var x;x = 6;Variables names must begin with a letter or underscoreVariable names are case-sensitive. All JavaScript identifiers are case sensitive.The variables lastName and lastname, are two different variables.lastName = "Doe";lastname = "Peterson";Variables are untyped (they can hold values of any type)Variables declared within a function are local to that function (accessible only within that function)Variables declared outside a function are global (accessible from anywhere on the page)JavaScript and Camel CaseHistorically, programmers have used three ways of joining multiple words into one variable name:Hyphens:first-name, last-name, master-card, inter-city.Underscore:first_name, last_name, master_card, inter_city.Camel Case:FirstName, LastName, MasterCard, InterCity.In programming languages, especially in JavaScript, camel case often starts with a lowercase letter:firstName, lastName, masterCard, interCity.Difference between Javascript Literal and Variable:JAVASCRIPT DATA TYPES JavaScript has three “primitive” types: number, string, and boolean Everything else is an object Numbers are always stored as floating-point values ◦ Hexadecimal numbers begin with 0x ◦ Some platforms treat 0123 as octal, others treat it as decimal Strings may be enclosed in single quotes or double quotes ◦ Strings can contains \n (newline), \" (double quote), etc. Booleans are either true or false ◦ 0, "0", empty strings, undefined, null, and NaN are false , other values are trueJavaScript Reserved WordsA list of all the reserved words in JavaScript are given in the following table. They cannot be used asJavaScript variables, functions, methods, loop labels, or any object names.abstract else instanceof switchboolean enum int synchronizedbreak export interface thisbyte extends long throwcase false native throwscatch final new transientchar finally null trueclass float package tryconst for private typeofcontinue function protected vardebugger goto public voiddefault if return volatiledelete implements short whiledo import static withdouble in superJAVASCRIPT OBJECTSReal Life Objects, Properties, and MethodsIn real life, a car is an object.A car has properties like weight and color, and methods like start and stop:Object Properties Methods car.name = Fiat car.start() car.model = 500 car.drive() car.weight = 850kg car.brake() car.color = white car.stop()All cars have the same properties, but the property values differ from car to car.All cars have the same methods, but the methods are performed at different times.Objects are variables too. But objects can contain many values.var car = {type:"Fiat", model:500, color:"white"};The values are written as name:value pairs (name and value separated by a colon).The name:values pairs (in JavaScript objects) are called properties.Methods are actions that can be performed on objects.Methods are stored in properties as function definitions.Accessing Object PropertiesYou can access object properties in two ways:objectName.propertyNameorobjectName[propertyName]Accessing Object MethodsYou access an object method with the following syntax:objectName.methodName()JAVASCRIPT OPERATORSArithmetic operators:+ - * / % ++ --Comparison operators:< <= == != >= >Logical operators:&& || ! (&& and || are short-circuit operators)Bitwise operators:& | ^ ~ << >> >>>Assignment operators:+= -= *= /= %= <<= >>= >>>= &= ^= |=Associativity.JAVASCRIPT EXPRESSIONSAn expression is any valid set of literals, variables, operators, and expressions that evaluates to asingle value. The value may be a number, a string, or a logical value. Conceptually, there are twotypes of expressions: those that assign a value to a variable, and those that simply have a value. Forexample, the expressionx=7is an expression that assigns x the value 7. This expression itself evaluates to 7. Such expressions useassignment operators. On the other hand, the expression3+4simply evaluates to 7; it does not perform an assignment. The operators used in such expressions arereferred to simply as operators.JavaScript has the following kinds of expressions: Arithmetic: evaluates to a number String: evaluates to a character string, for example "Fred" or "234" Logical: evaluates to true or falseThe special keyword null denotes a null value. In contrast, variables that have not been assigned avalue are undefined, and cannot be used without a run-time error.Conditional ExpressionsA conditional expression can have one of two values based on a condition. The syntax is(condition) ? val1 : val2If condition is true, the expression has the value of val1, Otherwise it has the value of val2. You canuse a conditional expression anywhere you would use a standard expression.For example,status = (age >= 18) ? "adult" : "minor"This statement assigns the value "adult" to the variable status if age is eighteen or greater. Otherwise,it assigns the value "minor" to status.JAVASCRIPT STATEMENTSAlgorithm : Any computing problem can be solved by executing a series of actions in a specificorder.A procedure for solving a problem in terms of1. the actions to be executed and2. the order in which the actions are to be executedis called an algorithm.PseudocodePseudocode is an artificial and informal language that helps programmers develop algo-rithms.Pseudocode is similar to everyday English; it is convenient and user friendly, although it is not anactual computer program-ming language.JavaScript statements are "instructions" to be "executed" by the web browser.JavaScript ProgramsMost JavaScript programs contain many JavaScript statements.The statements are executed, one by one, in the same order as they are written.Semicolons ;Semicolons separate JavaScript statements.JavaScript White SpaceJavaScript ignores multiple spaces. You can add white space to your script to make it more readable.JavaScript Line Length and Line BreaksFor best readability, programmers often like to avoid code lines longer than 80 characters.JAVASCRIPT CONTROL STATEMENTS • Sequential execution – Statements execute in the order they are written • Transfer of control – Next statement to execute may not be the next one in sequence • Three control structures – Sequence structure – Selection structure • if • if…else • switch – Repetition structure • while • do…while • for • for…inif Selection Statement • Single-entry/single-exit structure • Indicate action only when the condition evaluates to trueif…else Selection Statement • Indicate different actions to be perform when condition is true or false • Conditional operator (?:) – JavaScript’s only ternary operator • Three operands • Forms a conditional expression • Dangling-else problemswitch Multiple-Selection Statement • Controlling expression • Case labels • Default casewhile Repetition Statement • Repetition structure (loop) – Repeat action while some condition remains truedo…while Repetition Statement • Similar to the while statement • Tests the loop continuation condition after the loop body executes • Loop body always executes at least oncebreak and continue Statements • break – Immediate exit from the structure – Used to escape early from a loop – Skip the remainder of a switch statement • continue – Skips the remaining statements in the body of the structure – Proceeds with the next iteration of the loopLabeled break and continue Statements • Labeled break statement – Break out of a nested set of structures – Immediate exit from that structure and enclosing repetition structures – Execution resumes with first statement after enclosing labeled statement • Labeled continue statement – Skips the remaining statements in structure’s body and enclosing repetition structures – Proceeds with next iteration of enclosing labeled repetition structure – Loop-continuation test evaluates immediately after the continue statement executesfor Repetition Statement • It is a repetition statement – Handles all the details of counter-controlled repetition – for structure header • The first lineExample<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Class Average Program --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Class Average Program</title> <script type = "text/javascript"> <!-- var total, // sum of grades gradeCounter, // number of grades entered gradeValue, // grade value average, // average of all grades grade; // grade typed by user // Initialization Phase total = 0; // clear total gradeCounter = 1; // prepare to loop // Processing Phase while ( gradeCounter <= 10 ) { // loop 10 times // prompt for input and read grade from user grade = window.prompt( "Enter integer grade:", "0" ); // convert grade from a string to an integer gradeValue = parseInt( grade ); // add gradeValue to total total = total + gradeValue; // add 1 to gradeCounter gradeCounter = gradeCounter + 1; } // Termination Phase average = total / 10; // calculate the average // display average of exam grades document.writeln( "<h1>Class average is " + average + "</h1>" ); // --> </script>JAVASCRIPT FUNCTIONS • Functions – Started by function call – Receive necessary information via arguments (parameters) – Boss-Worker relationship • Calling function • Called function • Return value when finished • Can have many tiersDefining functions – All variables declared in function are called local • Do not exist outside current function – Parameters • Also local variables – Promotes reusability • Keep short • Name clearlyFormat of a function definitionfunction function-name( parameter-list ){ declarations and statements} – Function name any valid identifier – Parameter list names of variables that will receive arguments • Must have same number as function call • May be empty – Declarations and statements • Function body (“block” of code)Returning control – return statement – Can return either nothing, or a value return expression; – No return statement same as return; – Not returning a value when expected is an errorJavaScript Global Functions Global function Description escape This function 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 are encoded in a hexadecimal format that can be represented on all platforms. eval This function 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. isFinite This function takes a numeric argument and returns true if the value of the argument is not NaN, Number.POSITIVE_INFINITY or Number.NEGATIVE_INFINITY; otherwise, the function returns false. isNaN This function 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. parseFloat This function 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 123.45). parseInt This function 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. unescape This function takes a string as its argument and returns a string in which all characters previously encoded with escape are decoded.ExampleSquare of the numbers from 1 to 10 (jsfunc.html) <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>A Programmer-Defined square Function</title> <script type = "text/javascript"> <!-- document.writeln( "<h1>Square the numbers from 1 to 10</h1>" ); // square the numbers from 1 to 10 for ( var x = 1; x <= 10; ++x ) document.writeln( "The square of " + x + " is " + square( x ) + "<br />" ); // The following square function's body is executed // only when the function is explicitly called. // square function definition function square( y ) { return y * y; } // --> </script> </head><body></body> </html>JAVASCRIPT EVENTS • Events are the actions that occur as a result of browser activities or user interactions with the web pages. – Such as the user performs an action (mouse click or enters data) – We can validate the data entered by a user in a web form – Communicate with Java applets and browser plug-insEvent Categories • Keyboard and mouse events – Capturing a mouse event is simple • Load events – The page first appears on the screen: “Loads”, leaves: “Unloads”, … • Form-related events – onFocus() refers to placing the cursor into the text input in the form. • Others – Errors, window resizing.HTML elements HTML tags JavaScript Description defined eventsLink <a> click Mouse is clicked on a link dblClick Mouse is double-clicked on a link mouseDown Mouse button is pressed mouseUp Mouse button is released mouseOver Mouse is moved over a linkImage <img> load Image is loaded into a browser abort Image loading is abandoned error An error occurs during the image loadingArea <area> mouseOver The mouse is moved over an image map area mouseOut The mouse is moved from image map to dblClick outside The mouse is double-clicked on an image mapForm <form> submit The user submits a form Reset The user refreshes a form… … … …Event Handler • When an event occurs, a code segment is executed in response to a specific event is called “event handler”. • Event handler names are quite similar to the name of events they handle. • E.g the event handler for the “click” event is “onClick”. • <HTMLtag eventhandler=“JavaScript Code”>Event Handlers Triggered whenonChange The value of the text field, textarea, or a drop down list is modifiedonClick A link, an image or a form element is clicked onceonDblClick The element is double-clickedonMouseDown The user presses the mouse buttononLoad A document or an image is loadedonSubmit A user submits a formonReset The form is resetonUnLoad The user closes a document or a frameonResize A form is resized by the userExampleOnClick- Event Handler (jseveonclick.html)<html> <head> <script type="text/javascript"> <!-- function sayHello() { alert("Hello World") } //--> </script> </head> <body> <p>Click the following button and see result</p> <form> <input type="button" onclick="sayHello()" value="Say Hello" /> </form> </body></html>onLoad event Handler (jsevelo.html)<!DOCTYPE html><html><body onload="initial()" onunload="myFunction()"><h1>Welcome to my Home Page</h1><p>Close this window or press F5 to reload the page.</p><p><strong>Note:</strong> Due to different browser settings, this event may not always work asexpected.</p><script>function initial(){alert("Welcome to the page");}function myFunction() { alert("Thank you for visiting!");}</script></body></html>OnloadUnloadOnmouseout and onmouseover (jsevemouse.html)<html> <head> <script type="text/javascript"> <!-- function over() { document.write ("Mouse Over"); } function out() { document.write ("Mouse Out"); } //--> </script> </head> <body> <p>Bring your mouse inside the division to see the result:</p> <div onmouseover="over()" onmouseout="out()"> <h2> This is inside the division </h2> </div> </body></html>Event bubbling The process whereby events fired on child elements “bubble” up to their parent elements When an event is fired on an element, it is first delivered to the element’s event handler (if any), then to the parent element’s event handler (if any) If you intend to handle an event in a child element alone, you should cancel the bubbling of the event in the child element’s event-handling code by using the cancelBubble property of the event objectJAVASCRIPT WINDOWS • JavaScript considers the browser window an object, which it calls the window objectCreating New Browser Windows • Opening New Windows with JavaScript – The JavaScript command to create a new browser window is WinObj=window.open(“url”,”name”,”features”) • The following are the components of the window.open() statement: – The WinObj variable is used to store the new windowobject. You can access methods and properties of the new object by using this name. – The first parameter of the window.open() method is a URL, which will be loaded into the new window. If it’s left blank, no web page will be loaded. In this case, you could use JavaScript to fill the window with content. – .The second parameter specifies a window name (here, WindowName). This is assigned to the window object’s name property and is used to refer to the window. – The third parameter is a list of optional features, separated by commas. You can customize the new window by choosing whether to include the toolbar, status line, and other features. This enables you to create a variety of “floating” windows, which might look nothing like a typical browser window • Setting the Features of a Pop-up Window – The feature list obeys the following syntax: “feature1=value1, feature2=value2…featureN=valueN” • The window.close() method closes a window. • Browsers don’t normally allow you to close the main browser window without the user’s permission; this method’s main purpose is for closing windows you have created. • For example, this statement closes a window called updatewindow: updatewindow.close();Moving and Resizing Window • window.moveTo() moves the window to a new position. The parameters specify the x (column) and y (row) position. • window.moveBy() moves the window relative to its current position. The x and y parameters can be positive or negative, and are added to the current values to reach the new position. • window.resizeTo() resizes the window to the width and height specified as parameters. • window.resizeBy() resizes the window relative to its current size. The parameters are used to modify the current width and heightUsing Timeouts • The window.setTimeout method enables you to specify a time delay and a command that will execute after the delay passes. • setTimeout() method, which has two parameters. • The first is a JavaScript statement, or group of statements, enclosed in quotes. • The second parameter is the time to wait in milliseconds (thousandths of seconds). • For example, the following statement displays an alert dialog box after 10 seconds: – ident=window.setTimeout(“alert(‘Time’s up!’)”,10000) • Before a timeout has elapsed, you can stop it with the clearTimeout() method, specifying the identifier of the timeout to stop: – window.clearTimeout(ident)Displaying Dialog Box • window.alert(message) displays an alert dialog box. This dialog box simply gives the user a message. • window.confirm(message) displays a confirmation dialog box. This displays a message and includes OK and Cancel buttons. This method returns true if OK is pressed and false if Cancel is pressed. • window.prompt(message,default) displays a message and prompts the user for input. It returns the text entered by the user. If the user does not enter anything, the default value is used.Creating New Browser Windows • Setting the Features of a Pop-up Window • Working with Pop-up Blockers – Pop-up blockers prevent pop-up windows from opening – You can have the browser check whether the pop-up window has been opened or notfunction popWin(url) { windowObj = window.open(“url”,”name”,”features”); test=(windowObj==null || typeof(windowObj)==“undefined) ? true : false; return test;}<a href=“url” onclick=“return(popWin(“url”))”>Link Text</a>Model and Modeless Window • A modal window is a window that prevents users from doing work in any other window or dialog box until the window is closed • A modeless window allows users to work in other dialog boxes and windows even if the window stays openJAVASCRIPT DOCUMENTSThe HTML DOM DocumentIn the HTML DOM object model, the document object represents your web page.The document object is the owner of all other objects in your web page.If you want to access objects in an HTML page, you always start with accessing the document object.Below are some examples of how you can use the document object to access and manipulate HTML.Difference between document.write and document.writeln method write() does NOT add a new line after each statement writeln() add a new line after each statementFinding HTML ElementsMethod Descriptiondocument.getElementById() Find an element by element iddocument.getElementsByTagName() Find elements by tag namedocument.getElementsByClassName() Find elements by class nameChanging HTML ElementsMethod Descriptionelement.innerHTML= Change the inner HTML of an elementelement.attribute= Change the attribute of an HTML elementelement.setAttribute(attribute,value) Change the attribute of an HTML elementelement.style.property= Change the style of an HTML elementAdding and Deleting ElementsMethod Descriptiondocument.createElement() Create an HTML elementdocument.removeChild() Remove an HTML elementdocument.appendChild() Add an HTML elementdocument.replaceChild() Replace an HTML elementdocument.write(text) Write into the HTML output streamAdding Events HandlersMethod Description Adding event handler code to an onclickdocument.getElementById(id).onclick=function(){code} eventFinding HTML ObjectsThe first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections, and properties.These are still valid in HTML5.Later, in HTML DOM Level 3, more objects, collections, and properties were added.Property Description DOMdocument.anchors Returns all <a> elements that have a name attribute 1document.applets Returns all <applet> elements (Deprecated in HTML5) 1document.baseURI Returns the absolute base URI of the document 3document.body Returns the <body> element 1document.cookie Returns the document's cookie 1document.doctype Returns the document's doctype 3document.documentElement Returns the <html> element 3document.documentMode Returns the mode used by the browser 3document.documentURI Returns the URI of the document 3document.domain Returns the domain name of the document server 1document.domConfig Obsolete. Returns the DOM configuration 3document.embeds Returns all <embed> elements 3document.forms Returns all <form> elements 1document.head Returns the <head> element 3document.images Returns all <img> elements 1document.implementation Returns the DOM implementation 3document.inputEncoding Returns the document's encoding (character set) 3document.lastModified Returns the date and time the document was updated 3document.links Returns all <area> and <a> elements that have a href attribute 1document.readyState Returns the (loading) status of the document 3document.referrer Returns the URI of the referrer (the linking document) 1document.scripts Returns all <script> elements 3document.strictErrorChecking Returns if error checking is enforced 3document.title Returns the <title> element 1document.URL Returns the complete URL of the document 1JAVASCRIPT FRAMES • The name attribute of a frame is used when creating links whose targets are designed to appear in specific frames • To reference a specific frame in you JavaScript code, you need to use the id attribute <frame id=“top” name=“top” src=“home.htm” /> • Working with the frame and frameset objects – Each frame in a frameset is part of the frames collection windowObject.frames[idref] – To reference the header frame window.frames[0] window.framses[“header”] • Navigating between frames – JavaScript treats the frames in a frameset as elements in a hierarchical tree – The parent keyword refers to any object that is placed immediately above another object in the hierarchy – If you want to go directly to the top of the hierarchy, you can use the top keyword • Treating frames as windows – In most cases JavaScript treats a frame as a separate browser window frameObject.document.write(content) frameObject.document.close() frameObject.location.href = “url” • Setting the frameset layout – In JavaScript frameset.rows = “text” frameset.cols = “text” Browser Object Model The Browser Object Model (BOM) is a larger representation of everything provided by the browser including the current document, location, history, frames, and any other functionality the browser may expose to JavaScript. The Browser Object Model is not standardized and can change based on different browsers. The BOM's most important task is managing browser windows and enabling communication between the windows. Therefore, the window object stands at the center of the BOM. Every HTML document loaded into a browser window becomes a Document object which is an object in the Browser Object Model (BOM). All nodes with their contents in the BOM can be modified or deleted, and new node can be created by Javascript. The Document Object Model (DOM) is standardized and is specific to current HTML document. It is subset of BOM. BOM is the catch-all category of JavaScript. There are many objects, methods, and properties that are not part of the DOM structure. For example, the URL of the current page or the identification string of the browser are defined on the window object.VERIFYING FORMSForm validation normally used to occur at the server, after the client had entered all the necessarydata and then pressed the Submit button.If the data entered by a client was incorrect or was simply missing, the server would have to send allthe data back to the client and request that the form be resubmitted with correct information.This was really a lengthy process which used to put a lot of burden on the server.JavaScript provides a way to validate form's data on the client's computer before sending it to the webserver. Form validation generally performs two functions. Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data. Data Format Validation − Secondly, the data that is entered must be checked for correct form and value. Your code must include appropriate logic to test correctness of data.Example (vali_form.html)<html> <head> <title>Form Validation</title> <script type="text/javascript"> <!-- // Form validation code will come here. function validate() { var emailID = document.myForm.EMail.value; atpos = emailID.indexOf("@"); dotpos = emailID.lastIndexOf("."); if( document.myForm.Name.value == "" ) { alert( "Please provide your name!" ); document.myForm.Name.focus() ; return false; } if( document.myForm.EMail.value == "" ) { alert( "Please provide your Email!" ); document.myForm.EMail.focus() ; return false; }if (atpos < 1 || ( dotpos - atpos < 2 )) { alert("Please enter correct email ID") document.myForm.EMail.focus() ; return false; } if( document.myForm.Zip.value == "" || isNaN( document.myForm.Zip.value ) || document.myForm.Zip.value.length != 5 ) { alert( "Please provide a zip in the format #####." ); document.myForm.Zip.focus() ; return false; } if( document.myForm.Country.value == "-1" ) { alert( "Please provide your country!" ); return false; } return( true ); } //--> </script></head><body> <form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());"> <table cellspacing="2" cellpadding="2" border="1"> <tr> <td align="right">Name</td> <td><input type="text" name="Name" /></td> </tr> <tr> <td align="right">EMail</td> <td><input type="text" name="EMail" /></td> </tr> <tr> <td align="right">Zip Code</td> <td><input type="text" name="Zip" /></td> </tr> <tr> <td align="right">Country</td> <td> <select name="Country"> <option value="-1" selected>[choose yours]</option> <option value="1">USA</option> <option value="2">UK</option> <option value="3">INDIA</option> </select> </td> </tr> <tr> <td align="right"></td> <td><input type="submit" value="Submit" /></td> </tr> </table> </form> </body></html>HTML5HTML5 Introduction • Successor of HTML 4.01 and XHTML 1.1 • It comes with new tags, features and APIs • Below is a non exhaustive list of features that tend to be labelled as "HTML5" in the medias: – New structural elements (<header>, <footer>, <nav> and more) – Forms 2.0 and client-side validation – Native browser support for audio and video (<video>, <audio>) – Canvas API and SVG – Web storage – Offline applications – Geolocation – Drag & Drop – Web Workers – New communications API (Server Sent Events, Web Sockets, …)History • December 1997: HTML 4.0 is published by the W3C • February - March 1998: XML 1.0 is published • December 1999 - January 2000: ECMAScript 3rd Edition, XHTML 1.0 (Basically HTML tags reformulated in XML) and, HTML 4.01 recommendations are published • May 2001: XHTML 1.1 recommendation is published • August 2002: XHTML 2.0 first working draft is released. • December 2002: XHTML 2.0 second working draft published. • January 2008: First W3C working draft of HTML5 is published!!Future of HTML5 • 84% of Developers Plan to Adopt Key HTML5 Features • The key to understanding HTML5 is that it is not one, but a group of technologies. Within HTML5, developers have a tremendous amount of choice regarding what they use and what they don’t use • The power of HTML5 being ready for prime-time can be seen in Microsoft’s choice to utilize it in Windows 8New and Updated HTML5 ElementsHTML5 introduces 28 new elements: <section>, <article>, <aside>, <hgroup>, <header>,<footer>, <nav>, <figure>, <figcaption>, <video>, <audio>, <source>, <embed>, <mark>,<progress>, <meter>, <time>, <ruby>, <rt>, <rp >,<wbr>, <canvas>, <command>, <details>,<summary>, <datalist>, <keygen> and <output> An HTML page first starts with the DOCTYPE declaration HTML5 also update some of the previous existing elements to better reflect how they are used on the Web or to make them more useful such as: • The <a> element can now also contain flow content instead of just phrasing content • The <hr> element is now representing a paragraph-level thematic break • The <cite> element only represent the title of a work • The <strong> element is now representing importance rather than strong emphasis HTML5 offers new elements for better document structure:Tag Description<article> Defines an article in the document<aside> Defines content aside from the page content<bdi> Defines a part of text that might be formatted in a different direction from other text<details> Defines additional details that the user can view or hide<dialog> Defines a dialog box or window<figcaption> Defines a caption for a <figure> element<figure> Defines self-contained content, like illustrations, diagrams, photos, code listings, etc.<footer> Defines a footer for the document or a section<header> Defines a header for the document or a section<main> Defines the main content of a document<mark> Defines marked or highlighted text<menuitem> Defines a command/menu item that the user can invoke from a popup menu<meter> Defines a scalar measurement within a known range (a gauge)<nav> Defines navigation links in the document<progress> Defines the progress of a task<rp> Defines what to show in browsers that do not support ruby annotations<rt> Defines an explanation/pronunciation of characters (for East Asian typography)<ruby> Defines a ruby annotation (for East Asian typography)<section> Defines a section in the document<summary> Defines a visible heading for a <details> element<time> Defines a date/time<wbr> Defines a possible line-breakNew Form ElementsTag Description<datalist> Defines pre-defined options for input controls<keygen> Defines a key-pair generator field (for forms)<output> Defines the result of a calculationNew Input TypesNew Input Types New Input Attributes color autocomplete date autofocus datetime form datetime-local formaction email formenctype month formmethod number formnovalidate range formtarget search height and width tel list time min and max url multiple week pattern (regexp) placeholder required stepHTML5 - New Attribute SyntaxHTML5 allows four different syntaxes for attributes.Type ExampleEmpty <input type="text" value="John" disabled>Unquoted <input type="text" value=John>Double- <input type="text" value="John Doe">quotedSingle-quoted <input type="text" value='John Doe'>HTML5 GraphicsTag Description<canvas> Defines graphic drawing using JavaScript<svg> Defines graphic drawing using SVGNew Media ElementsTag Description<audio> Defines sound or music content<embed> Defines containers for external applications (like plug-ins)<source> Defines sources for <video> and <audio><track> Defines tracks for <video> and <audio><video> Defines video or movie contentSemantic ElementsMany web sites contain HTML code like: <div id="nav"> <div class="header"> <div id="footer">to indicate navigation, header, and footer.HTML5 offers new semantic elements to define different parts of a web page: <article> <aside> <details> <figcaption> <figure> <footer> <header> <main> <mark> <nav> <section> <summary> <time>HTML5 <section> ElementThe <section> element defines a section in a document.HTML5 <article> ElementThe <article> element specifies independent, self-contained content.An article should make sense on its own, and it should be possible to read it independently from therest of the web site.Examples of where an <article> element can be used: Forum post Blog post Newspaper articleHTML5 <header> ElementThe <header> element specifies a header for a document or section.The <header> element should be used as a container for introductory content.HTML5 <footer> ElementThe <footer> element specifies a footer for a document or section.A <footer> element should contain information about its containing element.HTML5 <nav> ElementThe <nav> element defines a set of navigation links.The <nav> element is intended for large blocks of navigation links. However, not all links in adocument should be inside a <nav> element!HTML5 <aside> ElementThe <aside> element defines some content aside from the content it is placed in (like a sidebar).The aside content should be related to the surrounding content.HTML5 <figure> and <figcaption> ElementsIn books and newspapers, it is common to have captions with images.The purpose of a caption is to add a visual explanation to an image.Why Semantic HTML5 Elements?With HTML4, developers used their own favorite attribute names to style page elements:header, top, bottom, footer, menu, navigation, main, container, content, article, sidebar, topnav, ...This made it impossible for search engines to identify the correct web page content.With HTML5 elements like: <header> <footer> <nav> <section> <article>, this will become easier.HTML5 <progress><Progress>: The new "progress" element appears to be very similar to the "meter" element. It iscreated to indicate progress of a specific task. The progress can be either determinate OR interderminate. Which means, you can use"progress" element to indicate a progress that you do not even know how much more work is to bedone yet. Progress of Task A : <progress value="60" max="100">60%</progress>HTML5 <meter><meter>: "Meter" is a new element in HTML5 which represenet value of a known range as a gauge.The keyword here is "known range". That means, you are only allowed to use it when you are clearlyaware of its minimum value and maximum value.One example is score of rating. I would rate this movie <meter min="0" max="10" value="8">8 of10</meter>.HTML5 <mark><mark>: The mark <mark> element represents a run of text in one document marked or highlightedfor reference purposes, due to its relevance in another context. Basically, it is used to bring the reader's attention to a part of the text that might not have beenHTML5 CANVASWhat is HTML Canvas?The HTML <canvas> element is used to draw graphics, on the fly, via scripting (usually JavaScript).The <canvas> element is only a container for graphics. You must use a script to actually draw thegraphics.Canvas has several methods for drawing paths, boxes, circles, text, and adding images.With HTML5’s Canvas API, we can draw anything and not only the rectangles, all throughJavaScript. This can improve the performance of websites by avoiding the need to download imagesoff the network. With canvas, we can draw shapes and lines, arcs and text, gradients and patterns. Inaddition, canvas gives us the power to manipulate pixels in images and even video.The Canvas 2D Context spec is supported in:■ Safari 2.0+■ Chrome 3.0+■ Firefox 3.0+■ Internet Explorer 9.0+■ Opera 10.0+■ iOS (Mobile Safari) 1.0+■ Android 1.0+Canvas ExamplesA canvas is a rectangular area on an HTML page. By default, a canvas has no border and no content.The markup looks like this:<canvas id="myCanvas" width="200" height="100"></canvas>Basic Canvas Example<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas>Drawing with JavaScriptvar c = document.getElementById("myCanvas");var ctx = c.getContext("2d");ctx.fillStyle = "#FF0000";ctx.fillRect(0,0,150,75);Draw a Linevar c = document.getElementById("myCanvas");var ctx = c.getContext("2d");ctx.moveTo(0,0);ctx.lineTo(200,100);ctx.stroke();Draw a Circlevar c = document.getElementById("myCanvas");var ctx = c.getContext("2d");ctx.beginPath();ctx.arc(95,50,40,0,2*Math.PI);ctx.stroke();Draw a Textvar c = document.getElementById("myCanvas");var ctx = c.getContext("2d");ctx.font = "30px Arial";ctx.fillText("Hello World",10,50);Stroke Textvar c = document.getElementById("myCanvas");var ctx = c.getContext("2d");ctx.font = "30px Arial";ctx.strokeText("Hello World",10,50);Draw Linear Gradientvar c = document.getElementById("myCanvas");var ctx = c.getContext("2d");// Create gradientvar grd = ctx.createLinearGradient(0,0,200,0);grd.addColorStop(0,"red");grd.addColorStop(1,"white");// Fill with gradientctx.fillStyle = grd;ctx.fillRect(10,10,150,80);Draw Circular Gradientvar c = document.getElementById("myCanvas");var ctx = c.getContext("2d");// Create gradientvar grd = ctx.createRadialGradient(75,50,5,90,60,100);grd.addColorStop(0,"red");grd.addColorStop(1,"white");// Fill with gradientctx.fillStyle = grd;ctx.fillRect(10,10,150,80);Draw Imagevar c = document.getElementById("myCanvas");var ctx = c.getContext("2d");var img = document.getElementById("scream");ctx.drawImage(img,10,10);What is SVG? SVG stands for Scalable Vector Graphics SVG is used to define graphics for the Web SVG is a W3C recommendationThe HTML <svg> ElementThe HTML <svg> element (introduced in HTML5) is a container for SVG graphics.SVG has several methods for drawing paths, boxes, circles, text, and graphic images.SVG CircleExample<!DOCTYPE html><html><body><svg width="100" height="100"> <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" /></svg></body></html>SVG RectangleExample<svg width="400" height="100"> <rect width="400" height="100" style="fill:rgb(0,0,255);stroke-width:10;stroke:rgb(0,0,0)" /></svg>SVG Rounded RectangleExample<svg width="400" height="180"> <rect x="50" y="20" rx="20" ry="20" width="150" height="150" style="fill:red;stroke:black;stroke-width:5;opacity:0.5" /></svg>SVG StarExample<svg width="300" height="200"> <polygon points="100,10 40,198 190,78 10,78 160,198" style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;" /></svg>SVG LogoExample<svg height="130" width="500"> <defs> <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%"> <stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1" /> <stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" /> </linearGradient> </defs> <ellipse cx="100" cy="70" rx="85" ry="55" fill="url(#grad1)" /> <text fill="#ffffff" font-size="45" font-family="Verdana" x="50" y="86">SVG</text> Sorry, your browser does not support inline SVG.</svg>Differences Between SVG and CanvasSVG is a language for describing 2D graphics in XML.Canvas draws 2D graphics, on the fly (with a JavaScript).SVG is XML based, which means that every element is available within the SVG DOM. You canattach JavaScript event handlers for an element.In SVG, each drawn shape is remembered as an object. If attributes of an SVG object are changed,the browser can automatically re-render the shape.Canvas is rendered pixel by pixel. In canvas, once the graphic is drawn, it is forgotten by the browser.If its position should be changed, the entire scene needs to be redrawn, including any objects thatmight have been covered by the graphic.Comparison of Canvas and SVGThe table below shows some important differences between Canvas and SVG: Canvas SVG Resolution independent Resolution dependent Support for event handlers No support for event handlers Best suited for applications with large Poor text rendering capabilities rendering areas (Google Maps) You can save the resulting image as .png Slow rendering if complex (anything that or .jpg uses the DOM a lot will be slow) Well suited for graphic-intensive games Not suited for game applicationsCSSHTML markup can be used to represent Semantics: h1 means that an element is a top-level heading Presentation: h1 elements look a certain way It’s advisable to separate semantics from presentation because: It’s easier to present documents on multiple platforms (browser, cell phone, spoken, …) It’s easier to generate documents with consistent look Semantic and presentation changes can be made independently of one another (division of labor) User control of presentation is facilitated Cascading Style Sheets (CSS) Applies to (X)HTML as well as XML documents in generalA styled HTML documentCSS SelectorsCSS selectors allow you to select and manipulate HTML elements.CSS selectors are used to "find" (or select) HTML elements based on their id, class, type, attribute,and more.The element SelectorThe element selector selects elements based on the element name.You can select all <p> elements on a page like this: (all <p> elements will be center-aligned, with ared text color)Examplep{ text-align: center; color: red; }The id SelectorThe id selector uses the id attribute of an HTML element to select a specific element.An id should be unique within a page, so the id selector is used if you want to select a single, uniqueelement.To select an element with a specific id, write a hash character, followed by the id of the element.The style rule below will be applied to the HTML element with id="para1":Example#para1 { text-align: center; color: red;}The class SelectorThe class selector selects elements with a specific class attribute.To select elements with a specific class, write a period character, followed by the name of the class:In the example below, all HTML elements with class="center" will be center-aligned:Example.center { text-align: center; color: red; }You can also specify that only specific HTML elements should be affected by a class. In the examplebelow, all <p> elements with class="center" will be center-aligned:Examplep.center { text-align: center; color: red;}Grouping SelectorsIf you have elements with the same style definitions, like this:h1 { text-align: center; color: red;}h2 { text-align: center; color: red;}p{ text-align: center; color: red;}you can group the selectors, to minimize the code.To group selectors, separate each selector with a comma.In the example below we have grouped the selectors from the code above:Exampleh1, h2, p { text-align: center; color: red;}Three Ways to Insert CSSThere are three ways of inserting a style sheet: External style sheet Internal style sheet Inline styleExternal Style SheetWith an external style sheet, you can change the look of an entire website by changing just one file!Each page must include a reference to the external style sheet file inside the <link> element. The<link> element goes inside the head section:<head><link rel="stylesheet" type="text/css" href="mystyle.css"></head>An external style sheet can be written in any text editor. The file should not contain any html tags.The style sheet file must be saved with a .css extension. An example of a style sheet file called"myStyle.css", is shown below:body { background-color: lightblue;}h1 { color: navy; margin-left: 20px;}Internal Style SheetAn internal style sheet may be used if one single page has a unique style.Internal styles are defined within the <style> element, inside the head section of an HTML page:Example<head><style>body { background-color: linen;}h1 { color: maroon; margin-left: 40px;}</style></head>Inline StylesAn inline style may be used to apply a unique style for a single element.An inline style loses many of the advantages of a style sheet (by mixing content with presentation).Use this method sparingly!To use inline styles, add the style attribute to the relevant tag. The style attribute can contain any CSSproperty. The example shows how to change the color and the left margin of a <h1> element:Example<h1 style="color:blue;margin-left:30px;">This is a heading.</h1>Multiple Style SheetsIf some properties have been defined for the same selector in different style sheets, the value will beinherited from the more specific style sheet.For example, assume that an external style sheet has the following properties for the <h1> element:h1 { color: navy; margin-left: 20px;}then, assume that an internal style sheet also has the following property for the <h1> element:h1 { color: orange;}If the page with the internal style sheet also links to the external style sheet the properties for the<h1> element will be:color: orange;margin-left: 20px;The left margin is inherited from the external style sheet and the color is replaced by the internal stylesheet.Multiple Styles Will Cascade into OneStyles can be specified: in an external CSS file inside the <head> section of an HTML page inside an HTML elementCascading orderWhat style will be used when there is more than one style specified for an HTML element?Generally speaking we can say that all the styles will "cascade" into a new "virtual" style sheet by thefollowing rules, where number three has the highest priority: 1. Browser default 2. External and internal style sheets (in the head section) 3. Inline style (inside an HTML element)So, an inline style (inside an HTML element) has the highest priority, which means that it willoverride a style defined inside the <head> tag, or in an external style sheet, or in a browser (a defaultvalue).CSS3 IntroductionCSS3 is the latest standard for CSS.CSS3 is completely backwards-compatible with earlier versions of CSS.CSS3 has been split into "modules". It contains the "old CSS specification" (which has been split intosmaller pieces). In addition, new modules are added.Some of the most important CSS3 modules are: Selectors Box Model Backgrounds and Borders Image Values and Replaced Content Text Effects 2D/3D Transformations Animations Multiple Column Layout User InterfaceCSS3 border-radius PropertyIf you specify only one value for the border-radius property, this radius will be applied to all 4corners.However, you can specify each corner separately if you wish. Here are the rules: Four values: first value applies to top-left, second value applies to top-right, third value applies to bottom-right, and fourth value applies to bottom-left corner Three values: first value applies to top-left, second value applies to top-right and bottom-left, and third value applies to bottom-right Two values: first value applies to top-left and bottom-right corner, and the second value applies to top-right and bottom-left corner One value: all four corners are rounded equallyExample#rcorners4 { border-radius: 15px 50px 30px 5px; background: #8AC007; padding: 20px; width: 200px; height: 150px;}#rcorners5 { border-radius: 15px 50px 30px; background: #8AC007; padding: 20px; width: 200px; height: 150px;}#rcorners6 { border-radius: 15px 50px; background: #8AC007; padding: 20px; width: 200px; height: 150px;}CSS3 Rounded Corners Properties Property Description A shorthand property for setting all the four border-*-*-radiusborder-radius propertiesborder-top-left-radius Defines the shape of the border of the top-left cornerborder-top-right-radius Defines the shape of the border of the top-right cornerborder-bottom-right-radius Defines the shape of the border of the bottom-right cornerborder-bottom-left-radius Defines the shape of the border of the bottom-left cornerCSS3 border-image PropertyThe CSS3 border-image property allows you to specify an image to be used instead of the normalborder around an element.The property has three parts: 1. The image to use as the border 2. Where to slice the image 3. Define whether the middle sections should be repeated or stretchedCSS3 Border Properties Property Descriptionborder-image A shorthand property for setting all the border-image-* propertiesborder-image-source Specifies the path to the image to be used as a borderborder-image-slice Specifies how to slice the border imageborder-image-width Specifies the widths of the border image Specifies the amount by which the border image area extends beyondborder-image-outset the border box Specifies whether the border image should be repeated, rounded orborder-image-repeat stretchedCSS3 BackgroundsCSS3 contains a few new background properties, which allow greater control of the backgroundelement.In this chapter you will learn how to add multiple background images to one element.You will also learn about the following new CSS3 properties: background-size background-origin background-clipCSS3 Multiple BackgroundsCSS3 allows you to add multiple background images for an element, through the background-imageproperty.The different background images are separated by commas, and the images are stacked on top of eachother, where the first image is closest to the viewer.The following example has two background images, the first image is a flower (aligned to the bottomand right) and the second image is a paper background (aligned to the top-left corner):Example#example1 { background-image: url(img_flwr.gif), url(paper.gif); background-position: right bottom, left top; background-repeat: no-repeat, repeat;}Multiple background images can be specified using either the individual background properties (asabove) or the background shorthand property.The following example uses the background shorthand property (same result as example above):Example#example1 { background: url(img_flwr.gif) right bottom no-repeat, url(paper.gif) left top repeat;}CSS3 Background Properties Property Descriptionbackground A shorthand property for setting all the background properties in one declarationbackground-clip Specifies the painting area of the backgroundbackground-image Specifies one or more background images for an elementbackground-origin Specifies where the background image(s) is/are positionedbackground-size Specifies the size of the background image(s)CSS3 background-origin PropertyThe CSS3 background-origin property specifies where the background image is positioned.The property takes three different values: border-box - the background image starts from the upper left corner of the border padding-box - (default) the background image starts from the upper left corner of the padding edge content-box - the background image starts from the upper left corner of the contentCSS3 background-clip PropertyThe CSS3 background-clip property specifies the painting area of the background.The property takes three different values: border-box - (default) the background is painted to the outside edge of the border padding-box - the background is painted to the outside edge of the padding content-box - the background is painted within the content boxCSS3 ColorsCSS supports color names, hexadecimal and RGB colors.In addition, CSS3 also introduces: RGBA colors HSL colors HSLA colors opacityRGBA ColorsRGBA color values are an extension of RGB color values with an alpha channel - which specifies theopacity for a color.An RGBA color value is specified with: rgba(red, green, blue, alpha). The alpha parameter is anumber between 0.0 (fully transparent) and 1.0 (fully opaque).Example#p1 {background-color: rgba(255, 0, 0, 0.3);} /* red with opacity */HSL ColorsHSL stands for Hue, Saturation and Lightness.An HSL color value is specified with: hsl(hue, saturation, lightness). 1. Hue is a degree on the color wheel (from 0 to 360): o 0 (or 360) is red o 120 is green o 240 is blue 2. Saturation is a percentage value: 100% is the full color. 3. Lightness is also a percentage; 0% is dark (black) and 100% is white.Example: #p1 {background-color: rgba(255, 0, 0, 0.3);} /* red with opacity */HSLA ColorsHSLA color values are an extension of HSL color values with an alpha channel - which specifies theopacity for a color.An HSLA color value is specified with: hsla(hue, saturation, lightness, alpha), where the alphaparameter defines the opacity. The alpha parameter is a number between 0.0 (fully transparent) and1.0 (fully opaque).Example#p1 {background-color: hsla(120, 100%, 50%, 0.3);} /* green with opacity */OpacityThe CSS3 opacity property sets the opacity for a specified RGB value.The opacity property value must be a number between 0.0 (fully transparent) and 1.0 (fully opaque).Example: #p1 {background-color:rgb(255,0,0);opacity:0.6;} /* red with opacity */CSS3 GradientsCSS3 gradients let you display smooth transitions between two or more specified colors.CSS3 gradients you can reduce download time and bandwidth usage. In addition, elements withgradients look better when zoomed, because the gradient is generated by the browser.CSS3 defines two types of gradients: Linear Gradients (goes down/up/left/right/diagonally) Radial Gradients (defined by their center)CSS3 Linear GradientsTo create a linear gradient you must define at least two color stops. Color stops are the colors youwant to render smooth transitions among. You can also set a starting point and a direction (or anangle) along with the gradient effect.Example of Linear Gradient:Syntaxbackground: linear-gradient(direction, color-stop1, color-stop2, ...);ExampleA linear gradient from top to bottom: background: linear-gradient(red, blue); /* Standard syntax */A linear gradient from left to right: background: linear-gradient(to right, red , blue);A linear gradient that starts at top left (and goes to bottom right): background: linear-gradient(tobottom right, red , blue); /* Standard syntax */CSS3 Radial GradientsA radial gradient is defined by its center.To create a radial gradient you must also define at least two color stops.Example of Radial Gradient:Syntaxbackground: radial-gradient(shape size at position, start-color, ..., last-color);CSS3 Text ShadowThe CSS3 text-shadow property applies shadow to text.In its simplest use, you only specify the horizontal shadow (2px) and the vertical shadow (2px): text-shadow: h-shadow v-shadow blur-radius color|none|initial|inherit;CSS3 Box Shadow box-shadow: none|h-shadow v-shadow blur spread color |inset|initial|inherit;CSS3 Shadow PropertiesThe following table lists the CSS3 shadow properties: Property Descriptionbox-shadow Adds one or more shadows to an elementtext-shadow Adds one or more shadows to a textCSS3 2D TransformsThe following are 2D transformation methods: translate() rotate() scale() skewX() skewY() matrix()The translate() MethodThe translate() method moves an element from its current position (according to the parameters givenfor the X-axis and the Y-axis).The rotate() MethodThe rotate() method rotates an element clockwise or counter-clockwise according to a given degree.The scale() MethodThe scale() method increases or decreases the size of an element (according to the parameters givenfor the width and height).The skewX() MethodThe skewX() method skews an element along the X-axis by the given angle.The skewY() MethodThe skewY() method skews an element along the Y-axis by the given angle.The skew() MethodThe skew() method skews an element along the X and Y-axis by the given angles.T he matrix() MethodThe matrix() method combines all the 2D transform methods into one.CSS3 Transform PropertiesThe following table lists all the 2D transform properties: Property Descriptiontransform Applies a 2D or 3D transformation to an elementtransform-origin Allows you to change the position on transformed elements2D Transform Methods Function Descriptionmatrix(n,n,n,n,n,n) Defines a 2D transformation, using a matrix of six valuestranslate(x,y) Defines a 2D translation, moving the element along the X- and the Y-axistranslateX(n) Defines a 2D translation, moving the element along the X-axistranslateY(n) Defines a 2D translation, moving the element along the Y-axisscale(x,y) Defines a 2D scale transformation, changing the elements width and heightscaleX(n) Defines a 2D scale transformation, changing the element's widthscaleY(n) Defines a 2D scale transformation, changing the element's heightrotate(angle) Defines a 2D rotation, the angle is specified in the parameterskew(x-angle,y-angle) Defines a 2D skew transformation along the X- and the Y-axisskewX(angle) Defines a 2D skew transformation along the X-axisskewY(angle) Defines a 2D skew transformation along the Y-axisCSS3 TransitionsCSS3 transitions allows you to change property values smoothly (from one value to another), over agiven duration.Example: Mouse over the element below to see a CSS3 transition effectCSS3 Transition PropertiesThe following table lists all the transition properties: Property Description A shorthand property for setting the four transition properties into a singletransition propertytransition-delay Specifies a delay (in seconds) for the transition effect Specifies how many seconds or milliseconds a transition effect takes totransition-duration completetransition-property Specifies the name of the CSS property the transition effect is fortransition-timing- Specifies the speed curve of the transition effectfunctionWEBSITE CREATION USING TOOLSFew of the tools which helps for easy website creation are1. YolaWhat it does: Yola lets you build a basic website by picking a template and filling out a few simpleforms. Once you have a rough outline, you fine-tune your site with an in-place editing tool. Yola hasthe goods to let you really dig into the web. You can integrate your site with an impressive list ofthird-party services such as Google Maps and PayPal, Flickr for photo sharing and Picnik for photoediting.What it costs: The basic web-building tool and a Yola.com address are free. For extra features,better-looking templates and the ability to use your own domain name, the Yola Silver upgrade is$100 per year.2. JimdoWhat it does: Jimdo's free version does what a respectable website builder should do, and not muchelse. We suggest springing for the upgrades (which are reasonably priced) to unlock some coolbusiness features, such as custom newsletters to keep in touch with your customers, page-view stats,PayPal stores and password-protected employees-only pages.What it costs: Basic features and a Jimdo.com address are free. Jimdo Pro is $5 per month. JimdoBusiness is $15 per month, including unlimited data storage and online selling, two domain namesand business-specific site designs.3. WIXWhat it does: Wix lets you build a great-looking website in no time with its easy-to-use, what-you-see-is-what-you-get editor. Here's the downside: The web development tool is based on Adobe Flash,which works on most PCs but isn't supported by some mobile devices, including the all-powerfulApple iPad. If that isn't a problem for you, Wix has lots of elegant templates that are easy tocustomize and can fit every business need. Wix's image-heavy sites are especially great for photogalleries, which really show clients what your business can do. A new mobile tool lets you build asimple, smartphone-optimized site to reach on-the-go clients.What it costs: The full-featured website-building tool and Wix.com address are free. Paidsubscriptions, which let you do things like remove ads and link a site to your own domain name, run$5 to $16 per month.4. Intuit WebsitesWhat it does: Starting a business takes creativity, but maybe you're not the artistic type. Luckily,even the most design-challenged among us can squeeze a respectable-looking website out of Intuit'ssomewhat bland but reliable web-editing tool. A quick survey helps you pick a template that's basedon what your business does and your goals for the website. The template sorter goes into more detailthan many website builders that make you wade through thousands of templates. From there you cantinker with the look and layout, but with some quick text and picture entries you'll be well on yourway to a reasonable web presence.What it costs: The starter package is free for 30 days, then $5 per month. Business and Professionalpackages are $24 and $50 per month, respectively, and include features like custom domain names,online selling tools and search engine optimization. Insider's note: Intuit has several resaleagreements with large telecom companies like Verizon, so don't be afraid to dig around to find apackage discount.5. Google SitesWhat it does: This service can give you a simple Google web presence for free. But you probablydon't need that when there are better, faster and easier options from the likes of Facebook, Twitter andLinkedIn. What Google Sites does best happens outside the public eye. With this tool you can createprivate, team-based websites within your business--which turns that Google Apps account of yoursinto a powerful business organization tool. Google Sites puts nifty collaboration tools likeannouncements, documents and task lists in one online location, allowing you and your colleagues toaccess them from anywhere. It's a great way to bring some sanity to the startup chaos.What it costs: It's free.Source:http://www.sqa.org.uk/e-learning/ClientSide01CD/index.htmhttp://www.w3schools.com/http://www.entrepreneur.com/article/220447http://www.tutorialspoint.com/javascript/https://www.codeschool.com/paths/javascripthttp://www.htmlandcssbook.comPPT present in internet in regard to the above topicsBooks:1. Harvey Deitel, Abbey Deitel, Internet and World Wide Web: How To Program 5 th Edition.2. Michael Moncur, Sams Teach yourself Javascript in 24 hours3. Jeffrey C. Jackson, WEB TECHNOLOGIES A Computer Science PerspectiveYou might also likeUnit - 3 PHP - 1PDFNo ratings yetUnit - 3 PHP - 160 pagesAutoGen - The Automated Program GeneratorPDFNo ratings yetAutoGen - The Automated Program Generator196 pagesUNIT 3 KR Predicate LogicPDFNo ratings yetUNIT 3 KR Predicate Logic53 pagesC Programming and Data StructuresPDFNo ratings yetC Programming and Data Structures5 pagesTopic For The Class:: Knowledge and ReasoningPDFNo ratings yetTopic For The Class:: Knowledge and Reasoning41 pagesChapters 8 & 9 First-Order Logic: Dr. Daisy TangPDFNo ratings yetChapters 8 & 9 First-Order Logic: Dr. Daisy Tang76 pagesKnowledge Representation First Order LogicPDFNo ratings yetKnowledge Representation First Order Logic49 pagesQUESTION BANK UNIT 5 - Computer Organization and Architecture PDFNo ratings yetQUESTION BANK UNIT 5 - Computer Organization and Architecture 9 pagesApplication of First-Order Logic in Knowledge Based Systems PDFPDFNo ratings yetApplication of First-Order Logic in Knowledge Based Systems PDF7 pagesCS 4 - Knowledge Representation - First Order LogicPDFNo ratings yetCS 4 - Knowledge Representation - First Order Logic86 pagesArtificial Intelligence For R-2017 by Krishna Sankar P., Shangaranarayanee N. P., Nithyananthan S.PDF0% (1)Artificial Intelligence For R-2017 by Krishna Sankar P., Shangaranarayanee N. P., Nithyananthan S.8 pagesChapter 01: Types of Digital DataPDFNo ratings yetChapter 01: Types of Digital Data80 pagesPythonPDFNo ratings yetPython21 pagesKnowledge Representation Additional ReadingPDFNo ratings yetKnowledge Representation Additional Reading26 pagesm8 FolPDFNo ratings yetm8 Fol27 pagesML Unit-5PDFNo ratings yetML Unit-583 pagesPrompt Engineering For Vision Models Slides 1720084286PDFNo ratings yetPrompt Engineering For Vision Models Slides 172008428617 pagesComputer Organization & ArchitecturePDFNo ratings yetComputer Organization & Architecture49 pagesBlockchain Unit 1PDFNo ratings yetBlockchain Unit 113 pagesAll Pairs Shortest PathPDFNo ratings yetAll Pairs Shortest Path28 pagesWeb3 PresentationPDFNo ratings yetWeb3 Presentation32 pagesModule-5:: Network AnalysisPDFNo ratings yetModule-5:: Network Analysis22 pagesTf-Idf: David Kauchak cs160 Fall 2009PDFNo ratings yetTf-Idf: David Kauchak cs160 Fall 200951 pagesAinotes Module4 PartaPDFNo ratings yetAinotes Module4 Parta11 pages1-Introduction To Dynamic Web ContentPDFNo ratings yet1-Introduction To Dynamic Web Content34 pagesMining The Web Graph: Technical Seminar Presentation OnPDFNo ratings yetMining The Web Graph: Technical Seminar Presentation On15 pagesWeb Technologies MCQsPDFNo ratings yetWeb Technologies MCQs53 pagesNavies BayesPDFNo ratings yetNavies Bayes18 pagesPlanning and Search: Classical Planning: Planning Graphs, GraphplanPDFNo ratings yetPlanning and Search: Classical Planning: Planning Graphs, Graphplan22 pagesCh-4 Ensemble LearningPDFNo ratings yetCh-4 Ensemble Learning18 pagesch9 Ensemble LearningPDFNo ratings yetch9 Ensemble Learning19 pagesASP.NetPDFNo ratings yetASP.Net126 pagesIR - ModelsPDF100% (3)IR - Models58 pagesAgents & EnvironmentPDFNo ratings yetAgents & Environment24 pagesData Structure in PythonPDFNo ratings yetData Structure in Python36 pagesUnit 1PDFNo ratings yetUnit 180 pagesStatistics PresentationPDFNo ratings yetStatistics Presentation21 pagesUnit 1PDFNo ratings yetUnit 159 pagesCompiler Design MCQ - JavatpointPDFNo ratings yetCompiler Design MCQ - Javatpoint1 pageJavaPDFNo ratings yetJava149 pagesPredicate LogicPDFNo ratings yetPredicate Logic64 pagesUnit-3 (NLP)PDFNo ratings yetUnit-3 (NLP)28 pagesProlog Notes-CompletePDFNo ratings yetProlog Notes-Complete31 pagesPaper - II Web TechnologyPDFNo ratings yetPaper - II Web Technology248 pagesShort Report On Expert SystemsPDF100% (1)Short Report On Expert Systems12 pagesKnowledge Based Systems (Sistem Berbasis Pengetahuan) : Ir. Wahidin Wahab M.SC PH.DPDFNo ratings yetKnowledge Based Systems (Sistem Berbasis Pengetahuan) : Ir. Wahidin Wahab M.SC PH.D33 pagesProgramming Agents WilliamsPDFNo ratings yetProgramming Agents Williams31 pagesNta Ugc Net KEY TO SUCCESS in Computer SciencePDFNo ratings yetNta Ugc Net KEY TO SUCCESS in Computer Science61 pagesAI - Unit - 5PDFNo ratings yetAI - Unit - 525 pagesThe Complete Reference Java - Lecture Notes, Study Material and Important Questions, AnswersPDFNo ratings yetThe Complete Reference Java - Lecture Notes, Study Material and Important Questions, Answers208 pagesData Science Intervieew QuestionsPDF100% (1)Data Science Intervieew Questions16 pagesTechnical Seminar: Sapthagiri College of EngineeringPDFNo ratings yetTechnical Seminar: Sapthagiri College of Engineering18 pages4 - Vector Data ModelPDFNo ratings yet4 - Vector Data Model31 pagesWT Unit-1 To 5PDFNo ratings yetWT Unit-1 To 5188 pagesWeek 6: Introduction To Natural Language ProcessingPDFNo ratings yetWeek 6: Introduction To Natural Language Processing18 pagesPROGRAMMING in C UNIT-4 notesPDFNo ratings yetPROGRAMMING in C UNIT-4 notes26 pagesServices-Oriented SEPDFNo ratings yetServices-Oriented SE14 pagesOntology Engineering PDFPDFNo ratings yetOntology Engineering PDF25 pagesWeb Technology 2074-2080PDFNo ratings yetWeb Technology 2074-208034 pagesTextbook of Engineering ChemistryFrom EverandTextbook of Engineering ChemistryC. Parameswara MurthyNo ratings yetSemantic Web Unit-IIIPDFNo ratings yetSemantic Web Unit-III17 pagesSemantic Web Unit-IVPDFNo ratings yetSemantic Web Unit-IV19 pagesIrs Unit1PDFNo ratings yetIrs Unit115 pagesCompiler Design Unit-3 NotesPDFNo ratings yetCompiler Design Unit-3 Notes51 pagesCD Unit 1 NotesPDFNo ratings yetCD Unit 1 Notes78 pagesJudgement Against Telenor (ISP) For Convert2mp3.net - Denmark (2018)PDFNo ratings yetJudgement Against Telenor (ISP) For Convert2mp3.net - Denmark (2018)18 pagesWeb Services - MindmapPDFNo ratings yetWeb Services - Mindmap1 pageDice Resume CV Jason AzimPDFNo ratings yetDice Resume CV Jason Azim12 pagesComplete List of Web Accessibility Evaluation ToolsPDFNo ratings yetComplete List of Web Accessibility Evaluation Tools46 pagesFiddlerPDFNo ratings yetFiddler6 pagesHow To Marketing With MSGPDFNo ratings yetHow To Marketing With MSG18 pagesPrimeFaces ThemesPDFNo ratings yetPrimeFaces Themes23 pagesA Random PDF File GooglePDFNo ratings yetA Random PDF File Google2 pagesImageRUNNER 5020 - 6020 Series Remote UI GuidePDFNo ratings yetImageRUNNER 5020 - 6020 Series Remote UI Guide171 pagesAse - L1 PDFPDFNo ratings yetAse - L1 PDF22 pagesSqli AttacksPDFNo ratings yetSqli Attacks149 pagesEnglish Grammar Book Wizard Course77PDFNo ratings yetEnglish Grammar Book Wizard Course777 pagesSample Work1 UDRP ArticlePDF100% (1)Sample Work1 UDRP Article8 pagesCybersecurity Foundation Lab 5: Using Two-Factor Authentication To Secure The FirewallPDFNo ratings yetCybersecurity Foundation Lab 5: Using Two-Factor Authentication To Secure The Firewall30 pagesIntercepting Filter Design PatternPDF0% (1)Intercepting Filter Design Pattern8 pagesMedi-Caps University IndorePDFNo ratings yetMedi-Caps University Indore16 pagesAccessibility and Usability Guidelines For WebsitesPDFNo ratings yetAccessibility and Usability Guidelines For Websites36 pagesWordpress Cheat Sheet PDFPDFNo ratings yetWordpress Cheat Sheet PDF2 pagesAutomatic Data Master Server: Data Collection Server System Based On B/S StructurePDF100% (1)Automatic Data Master Server: Data Collection Server System Based On B/S Structure19 pagesHTML - Model Qn-FinalPDFNo ratings yetHTML - Model Qn-Final2 pagesGreasemonkeyPDFNo ratings yetGreasemonkey5 pagesNit Recruitment 2013 PDFPDFNo ratings yetNit Recruitment 2013 PDF15 pagesAdobe CS6 Web EditionPDFNo ratings yetAdobe CS6 Web Edition3 pagesPosture Cisco ISEPDFNo ratings yetPosture Cisco ISE146 pagesDeveloping Business ModelPDFNo ratings yetDeveloping Business Model31 pagesLong Answer QuestionPDFNo ratings yetLong Answer Question6 pagesEthical Hacking Syllabus PDFPDF50% (2)Ethical Hacking Syllabus PDF2 pagesUsing The Google Chart Tools With RPDFNo ratings yetUsing The Google Chart Tools With R40 pagesChapter 6 Getting Data From The Client (Form Handling)PDFNo ratings yetChapter 6 Getting Data From The Client (Form Handling)43 pagesTechnical Infrastructure GuidePDFNo ratings yetTechnical Infrastructure Guide50 pagesDocumentsComputersInternet & Web
Web Programming Unit-1 Notes
AI-enhanced description
Type Descriptiontext Defines normal text inputradio Defines radio button input (for selecting one of many choices)submit Defines a submit button (for submitting the form)
Text Input<input type="text"> defines a one-line input field for text input
HTML Frameset: The <frameset> tag is not supported in HTML5.
The <frameset> element holds one or more <frame> elements. Each <frame> element can hold a separate document.
The <frameset> element specifies HOW MANY columns or rows there will be in the frameset, and HOW MUCH percentage/pixels of space will occupy each of them.
Example
<frameset cols="25%,*,25%"> <frame src="frame_a.htm"> <frame src="frame_b.htm"> <frame src="frame_c.htm"> </frameset>
SCRIPTING BASICS A scripting language is a form of programming language that is usually interpreted rather than compiled. Conventional programs are converted permanently into executable files before they are run. In contrast, programs in scripting language are interpreted one command at a time. Scripting languages are often written to facilitate enhanced features of Web sites. These features are processed on the server but the script in a specific page runs on the user's browser.In most cases, it is easier to write the code in a scripting language than in a compiled language.However, scripting languages are slower because the instructions are not handled solely by the basicinstruction processor.Scripting languages allow rapid development and can communicate easily with programs written inother languages.Scripting languages can be used to create specialized GUIs (graphical user interfaces) and forms thatenhance the convenience of search engines, Web-based e-mail and e-commerce.Many Web sites require that the user's browser be set to run scripts to take advantage of all thefeatures of the site. In some cases, Web sites are practically useless unless the user's computer is setto run programs locally in a scripting language.Client-side Scripting Environment (Browsers and Editors)The World Wide Web (WWW) began as a text-only medium-the first browsers didn't even supportimages within web pages.Today's websites can include a lot of features: graphics, sounds, animation, video, and occasionallyuseful content.Web scripting languages also known as client-side scripting languages, such as JavaScript, are one ofthe easiest ways to add dynamic state to a web page and to interact with users in new ways.HTML is a simple text markup language, it can't respond to the user, make decisions, or automaterepetitive tasks. Interactive tasks such as these require a more sophisticated language: a programminglanguage, or a scripting language.Although many programming languages are complex, scripting languages are generally simple. Theyhave a simple syntax, can perform tasks with a minimum of commands, and are easy to learn. Webscripting languages enable you to combine scripting with HTML to create interactive web pages.
Some programming languages must be compiled, or translated, into machine code before they can beexecuted. Client-side scripts, on the other hand, are an interpreted language: The browser executeseach line of script as it comes to it.There is one main advantage to interpreted languages: Writing or changing a script is very simple.Changing a client-side script is as easy as changing a typical HTML document, and the change isexecuted as soon as you refresh the document in the browser.
JavaScript was developed by Netscape Communications Corporation, the maker of the Netscape webbrowser. JavaScript was the first web scripting language to be supported by browsers, and it is still byfar the most popular.JavaScript was originally called LiveScript and was first introduced in Netscape Navigator 2.0 in1995. Netscape Navigator was an early browser that held a large share of the browser market. It wassoon renamed JavaScript to indicate a marketing relationship with Sun's Java language.JavaScript is almost as easy to learn as HTML, and it can be included directly in HTML documents.
Here are simple steps to turn on or turn off JavaScript in your Internet Explorer − Follow Tools → Internet Options from the menu. Select Security tab from the dialog box. Click the Custom Level button. Scroll down till you find Scripting option. Select Enable radio button under Active scripting. Finally click OK and come outTo disable JavaScript support in your Internet Explorer, you need to select Disable radio button underActive scripting.
JavaScript in Firefox
JavaScript in Chrome
JavaScript in Opera
If you have to do something important using JavaScript, then you can display a warning message tothe user using <noscript> tags.You can add a noscript block immediately after the script block as follows −
<html> <body> <script language="javascript" type="text/javascript"> <!-- document.write("Hello World!") //--> </script> <noscript> Sorry...JavaScript is needed to go ahead. </noscript> </body></html>Now, if the user's browser does not support JavaScript or JavaScript is not enabled, then the messagefrom </noscript> will be displayed on the screen.
JavaScript Programs
JAVASCRIPT STATEMENTS
JavaScript Values
The JavaScript syntax defines two types of values: Fixed values and variable values.Fixed values are called literals. Variable values are called variables.
JavaScript Literals
Array literals Boolean literals Floating-point literals Integers Object literals String literals
In Javascript an array literal is a list of expressions, each of which represents an array element,enclosed in a pair of square brackets ' [ ] ' . When an array is created using an array literal, it isinitialized with the specified values as its elements, and its length is set to the number of argumentsspecified. If no value is supplied it creates an empty array with zero length.
There is no need to specify all elements in an array literal. If we put two commas in a row at anyposition in an array then an unspecified element will be created in that place.The following example creates the fruits array :fruits = ["Orange", , "Mango"]This array has one empty element in the middle and two elements with values. ( fruits[0] is "Orange",fruits[1] is set to undefined, and fruits[2] is "Mango").If you include a single comma at the end of the elements, the comma is ignored. In the followingexample, the length of the array is three. There is no fruits[2].fruits = ["Orange", "Mango",]In the following example, the length of the array is four, and fruits[0] and fruits[2] are undefined.fruits = [ , 'Apple', , 'Orange'];
8.2935 -14.72
An object literal is zero or more pairs of comma separated list of property names and associatedvalues, enclosed by a pair of curly braces.In JavaScript an object literal is declared as follows:1. An object literal without properties:var userObject = {}2. An object literal with a few properties :var student = {First-name : "Suresy",Last-name : "Rayy",Roll-No : 12};
Syntax Rules
JavaScript has its own way to deal with string literals. A string literal is zero or more characters,either enclosed in single quotation (') marks or double quotation (") marks. You can also use +operator to join strings. The following are the examples of string literals : string1 = "w3resource.com" string1 = 'w3resource.com' string1 = "1000" string1 = "google" + ".com"In addition to ordinary characters, you can include special characters in strings, as shown in thefollowing table.string1 = "First line. \n Second line."
Character Meaning
\b Backspace
\f Form feed
\n New line
\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.
\t Tab
The character with the Latin-1 encoding specified by up to three octal digits\XXX XXX between 0 and 377. For example, \100 is the octal sequence for the @ symbol.
The character with the Latin-1 encoding specified by the two hexadecimal\xXX digits XX between 00 and FF. For example, \x40 is the hexadecimal sequence for the @ symbol.
The Unicode character specified by the four hexadecimal digits XXXX. For\uXXXX example, \u0040 is the Unicode sequence for the @ symbol.
10.50
1001
lastName = "Doe";lastname = "Peterson";Variables are untyped (they can hold values of any type)
Variables declared within a function are local to that function (accessible only within that function)Variables declared outside a function are global (accessible from anywhere on the page)
Historically, programmers have used three ways of joining multiple words into one variable name:Hyphens:first-name, last-name, master-card, inter-city.Underscore:first_name, last_name, master_card, inter_city.Camel Case:FirstName, LastName, MasterCard, InterCity.In programming languages, especially in JavaScript, camel case often starts with a lowercase letter:firstName, lastName, masterCard, interCity.
◦ 0, "0", empty strings, undefined, null, and NaN are false , other values are true
A list of all the reserved words in JavaScript are given in the following table. They cannot be used asJavaScript variables, functions, methods, loop labels, or any object names.
double in super
JAVASCRIPT OBJECTS
All cars have the same properties, but the property values differ from car to car.All cars have the same methods, but the methods are performed at different times.
Objects are variables too. But objects can contain many values.var car = {type:"Fiat", model:500, color:"white"};The values are written as name:value pairs (name and value separated by a colon).The name:values pairs (in JavaScript objects) are called properties.
JAVASCRIPT OPERATORS
Arithmetic operators:+ - * / % ++ --Comparison operators:< <= == != >= >Logical operators:&& || ! (&& and || are short-circuit operators)Bitwise operators:& | ^ ~ << >> >>>Assignment operators:+= -= *= /= %= <<= >>= >>>= &= ^= |=Associativity.JAVASCRIPT EXPRESSIONS
An expression is any valid set of literals, variables, operators, and expressions that evaluates to asingle value. The value may be a number, a string, or a logical value. Conceptually, there are twotypes of expressions: those that assign a value to a variable, and those that simply have a value. Forexample, the expressionx=7is an expression that assigns x the value 7. This expression itself evaluates to 7. Such expressions useassignment operators. On the other hand, the expression3+4simply evaluates to 7; it does not perform an assignment. The operators used in such expressions arereferred to simply as operators.JavaScript has the following kinds of expressions:
The special keyword null denotes a null value. In contrast, variables that have not been assigned avalue are undefined, and cannot be used without a run-time error.
Conditional Expressions
A conditional expression can have one of two values based on a condition. The syntax is
If condition is true, the expression has the value of val1, Otherwise it has the value of val2. You canuse a conditional expression anywhere you would use a standard expression.For example,
Semicolons ;
JavaScript ignores multiple spaces. You can add white space to your script to make it more readable.
For best readability, programmers often like to avoid code lines longer than 80 characters.JAVASCRIPT CONTROL STATEMENTS • Sequential execution – Statements execute in the order they are written • Transfer of control – Next statement to execute may not be the next one in sequence • Three control structures – Sequence structure – Selection structure • if • if…else • switch – Repetition structure • while • do…while • for • for…in
if Selection Statement • Single-entry/single-exit structure • Indicate action only when the condition evaluates to trueif…else Selection Statement • Indicate different actions to be perform when condition is true or false • Conditional operator (?:) – JavaScript’s only ternary operator • Three operands • Forms a conditional expression • Dangling-else problemswitch Multiple-Selection Statement • Controlling expression • Case labels • Default casewhile Repetition Statement • Repetition structure (loop) – Repeat action while some condition remains truedo…while Repetition Statement • Similar to the while statement • Tests the loop continuation condition after the loop body executes • Loop body always executes at least oncebreak and continue Statements • break – Immediate exit from the structure – Used to escape early from a loop – Skip the remainder of a switch statement • continue – Skips the remaining statements in the body of the structure – Proceeds with the next iteration of the loopLabeled break and continue Statements • Labeled break statement – Break out of a nested set of structures – Immediate exit from that structure and enclosing repetition structures – Execution resumes with first statement after enclosing labeled statement • Labeled continue statement – Skips the remaining statements in structure’s body and enclosing repetition structures – Proceeds with next iteration of enclosing labeled repetition structure – Loop-continuation test evaluates immediately after the continue statement executesfor Repetition Statement • It is a repetition statement – Handles all the details of counter-controlled repetition – for structure header • The first line
Example<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Class Average Program --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Class Average Program</title> <script type = "text/javascript"> <!-- var total, // sum of grades gradeCounter, // number of grades entered gradeValue, // grade value average, // average of all grades grade; // grade typed by user // Initialization Phase total = 0; // clear total gradeCounter = 1; // prepare to loop // Processing Phase while ( gradeCounter <= 10 ) { // loop 10 times // prompt for input and read grade from user grade = window.prompt( "Enter integer grade:", "0" ); // convert grade from a string to an integer gradeValue = parseInt( grade ); // add gradeValue to total total = total + gradeValue; // add 1 to gradeCounter gradeCounter = gradeCounter + 1; } // Termination Phase average = total / 10; // calculate the average // display average of exam grades document.writeln( "<h1>Class average is " + average + "</h1>" ); // --> </script>JAVASCRIPT FUNCTIONS • Functions – Started by function call – Receive necessary information via arguments (parameters) – Boss-Worker relationship • Calling function • Called function • Return value when finished • Can have many tiers
Defining functions – All variables declared in function are called local • Do not exist outside current function – Parameters • Also local variables – Promotes reusability • Keep short • Name clearlyFormat of a function definitionfunction function-name( parameter-list ){ declarations and statements} – Function name any valid identifier – Parameter list names of variables that will receive arguments • Must have same number as function call • May be empty – Declarations and statements • Function body (“block” of code)Returning control – return statement – Can return either nothing, or a value return expression; – No return statement same as return; – Not returning a value when expected is an errorJavaScript Global Functions
parseInt This function 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. unescape This function takes a string as its argument and returns a string in which all characters previously encoded with escape are decoded.
ExampleSquare of the numbers from 1 to 10 (jsfunc.html) <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>A Programmer-Defined square Function</title> <script type = "text/javascript"> <!-- document.writeln( "<h1>Square the numbers from 1 to 10</h1>" ); // square the numbers from 1 to 10 for ( var x = 1; x <= 10; ++x ) document.writeln( "The square of " + x + " is " + square( x ) + "<br />" ); // The following square function's body is executed // only when the function is explicitly called. // square function definition function square( y ) { return y * y; } // --> </script> </head><body></body> </html>
JAVASCRIPT EVENTS • Events are the actions that occur as a result of browser activities or user interactions with the web pages. – Such as the user performs an action (mouse click or enters data) – We can validate the data entered by a user in a web form – Communicate with Java applets and browser plug-insEvent Categories • Keyboard and mouse events – Capturing a mouse event is simple • Load events – The page first appears on the screen: “Loads”, leaves: “Unloads”, … • Form-related events – onFocus() refers to placing the cursor into the text input in the form. • Others – Errors, window resizing.HTML elements HTML tags JavaScript Description defined events
… … … …
Event Handler • When an event occurs, a code segment is executed in response to a specific event is called “event handler”. • Event handler names are quite similar to the name of events they handle. • E.g the event handler for the “click” event is “onClick”. • <HTMLtag eventhandler=“JavaScript Code”>Event Handlers Triggered when
onChange The value of the text field, textarea, or a drop down list is modified
ExampleOnClick- Event Handler (jseveonclick.html)<html> <head> <script type="text/javascript"> <!-- function sayHello() { alert("Hello World") } //--> </script> </head> <body> <p>Click the following button and see result</p> <form> <input type="button" onclick="sayHello()" value="Say Hello" /> </form> </body></html>
Method Description
The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections, and properties.These are still valid in HTML5.Later, in HTML DOM Level 3, more objects, collections, and properties were added.
document.lastModified Returns the date and time the document was updated 3
document.links Returns all <area> and <a> elements that have a href attribute 1
JAVASCRIPT FRAMES • The name attribute of a frame is used when creating links whose targets are designed to appear in specific frames • To reference a specific frame in you JavaScript code, you need to use the id attribute <frame id=“top” name=“top” src=“home.htm” /> • Working with the frame and frameset objects – Each frame in a frameset is part of the frames collection windowObject.frames[idref] – To reference the header frame window.frames[0] window.framses[“header”] • Navigating between frames – JavaScript treats the frames in a frameset as elements in a hierarchical tree – The parent keyword refers to any object that is placed immediately above another object in the hierarchy – If you want to go directly to the top of the hierarchy, you can use the top keyword • Treating frames as windows – In most cases JavaScript treats a frame as a separate browser window frameObject.document.write(content) frameObject.document.close() frameObject.location.href = “url” • Setting the frameset layout – In JavaScript frameset.rows = “text” frameset.cols = “text” Browser Object Model
The Browser Object Model (BOM) is a larger representation of everything provided by the browser including the current document, location, history, frames, and any other functionality the browser may expose to JavaScript. The Browser Object Model is not standardized and can change based on different browsers. The BOM's most important task is managing browser windows and enabling communication between the windows. Therefore, the window object stands at the center of the BOM. Every HTML document loaded into a browser window becomes a Document object which is an object in the Browser Object Model (BOM). All nodes with their contents in the BOM can be modified or deleted, and new node can be created by Javascript.
The Document Object Model (DOM) is standardized and is specific to current HTML document. It is subset of BOM. BOM is the catch-all category of JavaScript. There are many objects, methods, and properties that are not part of the DOM structure. For example, the URL of the current page or the identification string of the browser are defined on the window object.VERIFYING FORMS
Form validation normally used to occur at the server, after the client had entered all the necessarydata and then pressed the Submit button.If the data entered by a client was incorrect or was simply missing, the server would have to send allthe data back to the client and request that the form be resubmitted with correct information.This was really a lengthy process which used to put a lot of burden on the server.JavaScript provides a way to validate form's data on the client's computer before sending it to the webserver. Form validation generally performs two functions. Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data. Data Format Validation − Secondly, the data that is entered must be checked for correct form and value. Your code must include appropriate logic to test correctness of data.
Example (vali_form.html)<html> <head> <title>Form Validation</title> <script type="text/javascript"> <!-- // Form validation code will come here. function validate() { var emailID = document.myForm.EMail.value; atpos = emailID.indexOf("@"); dotpos = emailID.lastIndexOf("."); if( document.myForm.Name.value == "" ) { alert( "Please provide your name!" ); document.myForm.Name.focus() ; return false; } if( document.myForm.EMail.value == "" ) { alert( "Please provide your Email!" ); document.myForm.EMail.focus() ; return false; }if (atpos < 1 || ( dotpos - atpos < 2 )) { alert("Please enter correct email ID") document.myForm.EMail.focus() ; return false; } if( document.myForm.Zip.value == "" || isNaN( document.myForm.Zip.value ) || document.myForm.Zip.value.length != 5 ) { alert( "Please provide a zip in the format #####." ); document.myForm.Zip.focus() ; return false; } if( document.myForm.Country.value == "-1" ) { alert( "Please provide your country!" ); return false; } return( true ); } //--> </script></head><body> <form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());"> <table cellspacing="2" cellpadding="2" border="1"> <tr> <td align="right">Name</td> <td><input type="text" name="Name" /></td> </tr> <tr> <td align="right">EMail</td> <td><input type="text" name="EMail" /></td> </tr> <tr> <td align="right">Zip Code</td> <td><input type="text" name="Zip" /></td> </tr> <tr> <td align="right">Country</td> <td> <select name="Country"> <option value="-1" selected>[choose yours]</option> <option value="1">USA</option> <option value="2">UK</option> <option value="3">INDIA</option> </select> </td> </tr> <tr> <td align="right"></td> <td><input type="submit" value="Submit" /></td> </tr> </table> </form> </body></html>HTML5HTML5 Introduction • Successor of HTML 4.01 and XHTML 1.1 • It comes with new tags, features and APIs • Below is a non exhaustive list of features that tend to be labelled as "HTML5" in the medias: – New structural elements (<header>, <footer>, <nav> and more) – Forms 2.0 and client-side validation – Native browser support for audio and video (<video>, <audio>) – Canvas API and SVG – Web storage – Offline applications – Geolocation – Drag & Drop – Web Workers – New communications API (Server Sent Events, Web Sockets, …)History • December 1997: HTML 4.0 is published by the W3C • February - March 1998: XML 1.0 is published • December 1999 - January 2000: ECMAScript 3rd Edition, XHTML 1.0 (Basically HTML tags reformulated in XML) and, HTML 4.01 recommendations are published • May 2001: XHTML 1.1 recommendation is published • August 2002: XHTML 2.0 first working draft is released. • December 2002: XHTML 2.0 second working draft published. • January 2008: First W3C working draft of HTML5 is published!!Future of HTML5 • 84% of Developers Plan to Adopt Key HTML5 Features • The key to understanding HTML5 is that it is not one, but a group of technologies. Within HTML5, developers have a tremendous amount of choice regarding what they use and what they don’t use • The power of HTML5 being ready for prime-time can be seen in Microsoft’s choice to utilize it in Windows 8New and Updated HTML5 ElementsHTML5 introduces 28 new elements: <section>, <article>, <aside>, <hgroup>, <header>,<footer>, <nav>, <figure>, <figcaption>, <video>, <audio>, <source>, <embed>, <mark>,<progress>, <meter>, <time>, <ruby>, <rt>, <rp >,<wbr>, <canvas>, <command>, <details>,<summary>, <datalist>, <keygen> and <output> An HTML page first starts with the DOCTYPE declaration HTML5 also update some of the previous existing elements to better reflect how they are used on the Web or to make them more useful such as: • The <a> element can now also contain flow content instead of just phrasing content • The <hr> element is now representing a paragraph-level thematic break • The <cite> element only represent the title of a work • The <strong> element is now representing importance rather than strong emphasis HTML5 offers new elements for better document structure:
Tag Description
<bdi> Defines a part of text that might be formatted in a different direction from other text
<details> Defines additional details that the user can view or hide
<figure> Defines self-contained content, like illustrations, diagrams, photos, code listings, etc.<footer> Defines a footer for the document or a section
<menuitem> Defines a command/menu item that the user can invoke from a popup menu
<rp> Defines what to show in browsers that do not support ruby annotations
color autocomplete date autofocus datetime form datetime-local formaction email formenctype month formmethod number formnovalidate range formtarget search height and width tel list time min and max url multiple week pattern (regexp) placeholder required step
Type Example
Double- <input type="text" value="John Doe">quoted
HTML5 Graphics
Semantic ElementsMany web sites contain HTML code like: <div id="nav"> <div class="header"> <div id="footer">to indicate navigation, header, and footer.HTML5 offers new semantic elements to define different parts of a web page: <article> <aside> <details> <figcaption> <figure> <footer> <header> <main> <mark> <nav> <section> <summary> <time>
The <aside> element defines some content aside from the content it is placed in (like a sidebar).
With HTML4, developers used their own favorite attribute names to style page elements:header, top, bottom, footer, menu, navigation, main, container, content, article, sidebar, topnav, ...This made it impossible for search engines to identify the correct web page content.With HTML5 elements like: <header> <footer> <nav> <section> <article>, this will become easier.
HTML5 <progress><Progress>: The new "progress" element appears to be very similar to the "meter" element. It iscreated to indicate progress of a specific task. The progress can be either determinate OR interderminate. Which means, you can use"progress" element to indicate a progress that you do not even know how much more work is to bedone yet. Progress of Task A : <progress value="60" max="100">60%</progress>HTML5 <meter><meter>: "Meter" is a new element in HTML5 which represenet value of a known range as a gauge.The keyword here is "known range". That means, you are only allowed to use it when you are clearlyaware of its minimum value and maximum value.One example is score of rating. I would rate this movie <meter min="0" max="10" value="8">8 of10</meter>.
HTML5 <mark><mark>: The mark <mark> element represents a run of text in one document marked or highlightedfor reference purposes, due to its relevance in another context. Basically, it is used to bring the reader's attention to a part of the text that might not have beenHTML5 CANVAS
The HTML <canvas> element is used to draw graphics, on the fly, via scripting (usually JavaScript).The <canvas> element is only a container for graphics. You must use a script to actually draw thegraphics.Canvas has several methods for drawing paths, boxes, circles, text, and adding images.
With HTML5’s Canvas API, we can draw anything and not only the rectangles, all throughJavaScript. This can improve the performance of websites by avoiding the need to download imagesoff the network. With canvas, we can draw shapes and lines, arcs and text, gradients and patterns. Inaddition, canvas gives us the power to manipulate pixels in images and even video.The Canvas 2D Context spec is supported in:■ Safari 2.0+■ Chrome 3.0+■ Firefox 3.0+■ Internet Explorer 9.0+■ Opera 10.0+■ iOS (Mobile Safari) 1.0+■ Android 1.0+
Canvas Examples
A canvas is a rectangular area on an HTML page. By default, a canvas has no border and no content.The markup looks like this:
var c = document.getElementById("myCanvas");var ctx = c.getContext("2d");ctx.fillStyle = "#FF0000";ctx.fillRect(0,0,150,75);Draw a Line
var c = document.getElementById("myCanvas");var ctx = c.getContext("2d");ctx.moveTo(0,0);ctx.lineTo(200,100);ctx.stroke();
Draw a Circle
var c = document.getElementById("myCanvas");var ctx = c.getContext("2d");ctx.beginPath();ctx.arc(95,50,40,0,2*Math.PI);ctx.stroke();
Draw a Text
var c = document.getElementById("myCanvas");var ctx = c.getContext("2d");ctx.font = "30px Arial";ctx.fillText("Hello World",10,50);
Stroke Text
var c = document.getElementById("myCanvas");var ctx = c.getContext("2d");ctx.font = "30px Arial";ctx.strokeText("Hello World",10,50);
var c = document.getElementById("myCanvas");var ctx = c.getContext("2d");// Create gradientvar grd = ctx.createLinearGradient(0,0,200,0);grd.addColorStop(0,"red");grd.addColorStop(1,"white");
var c = document.getElementById("myCanvas");var ctx = c.getContext("2d");
// Create gradientvar grd = ctx.createRadialGradient(75,50,5,90,60,100);grd.addColorStop(0,"red");grd.addColorStop(1,"white");
Draw Image
var c = document.getElementById("myCanvas");var ctx = c.getContext("2d");var img = document.getElementById("scream");ctx.drawImage(img,10,10);
What is SVG?
The HTML <svg> element (introduced in HTML5) is a container for SVG graphics.SVG has several methods for drawing paths, boxes, circles, text, and graphic images.
SVG CircleExample
<!DOCTYPE html><html><body>
</body></html>
SVG RectangleExample
SVG LogoExample
The table below shows some important differences between Canvas and SVG:
Canvas SVG
Resolution independent Resolution dependent Support for event handlers No support for event handlers Best suited for applications with large Poor text rendering capabilities rendering areas (Google Maps) You can save the resulting image as .png Slow rendering if complex (anything that or .jpg uses the DOM a lot will be slow) Well suited for graphic-intensive games Not suited for game applications
CSSHTML markup can be used to represent Semantics: h1 means that an element is a top-level heading Presentation: h1 elements look a certain way It’s advisable to separate semantics from presentation because: It’s easier to present documents on multiple platforms (browser, cell phone, spoken, …) It’s easier to generate documents with consistent look Semantic and presentation changes can be made independently of one another (division of labor) User control of presentation is facilitated Cascading Style Sheets (CSS) Applies to (X)HTML as well as XML documents in generalA styled HTML documentCSS Selectors
Examplep{ text-align: center; color: red; }
The id Selector
The id selector uses the id attribute of an HTML element to select a specific element.An id should be unique within a page, so the id selector is used if you want to select a single, uniqueelement.To select an element with a specific id, write a hash character, followed by the id of the element.The style rule below will be applied to the HTML element with id="para1":
#para1 { text-align: center; color: red;}The class Selector
Example.center { text-align: center; color: red; }
You can also specify that only specific HTML elements should be affected by a class. In the examplebelow, all <p> elements with class="center" will be center-aligned:
p.center { text-align: center; color: red;}Grouping SelectorsIf you have elements with the same style definitions, like this:h1 { text-align: center; color: red;}
h2 { text-align: center; color: red;}
p{ text-align: center; color: red;}
h1, h2, p { text-align: center; color: red;}
With an external style sheet, you can change the look of an entire website by changing just one file!Each page must include a reference to the external style sheet file inside the <link> element. The<link> element goes inside the head section:
<head><link rel="stylesheet" type="text/css" href="mystyle.css"></head>
An external style sheet can be written in any text editor. The file should not contain any html tags.The style sheet file must be saved with a .css extension. An example of a style sheet file called"myStyle.css", is shown below:
body { background-color: lightblue;}
h1 { color: navy; margin-left: 20px;}
An internal style sheet may be used if one single page has a unique style.Internal styles are defined within the <style> element, inside the head section of an HTML page:
<head><style>body { background-color: linen;}
h1 { color: maroon; margin-left: 40px;}</style></head>
Inline Styles
An inline style may be used to apply a unique style for a single element.An inline style loses many of the advantages of a style sheet (by mixing content with presentation).Use this method sparingly!To use inline styles, add the style attribute to the relevant tag. The style attribute can contain any CSSproperty. The example shows how to change the color and the left margin of a <h1> element:
If some properties have been defined for the same selector in different style sheets, the value will beinherited from the more specific style sheet.For example, assume that an external style sheet has the following properties for the <h1> element:
then, assume that an internal style sheet also has the following property for the <h1> element:
h1 { color: orange;}If the page with the internal style sheet also links to the external style sheet the properties for the<h1> element will be:
color: orange;margin-left: 20px;
The left margin is inherited from the external style sheet and the color is replaced by the internal stylesheet.
Cascading order
What style will be used when there is more than one style specified for an HTML element?Generally speaking we can say that all the styles will "cascade" into a new "virtual" style sheet by thefollowing rules, where number three has the highest priority:
1. Browser default 2. External and internal style sheets (in the head section) 3. Inline style (inside an HTML element)
So, an inline style (inside an HTML element) has the highest priority, which means that it willoverride a style defined inside the <head> tag, or in an external style sheet, or in a browser (a defaultvalue).
CSS3 IntroductionCSS3 is the latest standard for CSS.CSS3 is completely backwards-compatible with earlier versions of CSS.CSS3 has been split into "modules". It contains the "old CSS specification" (which has been split intosmaller pieces). In addition, new modules are added.Some of the most important CSS3 modules are: Selectors Box Model Backgrounds and Borders Image Values and Replaced Content Text Effects 2D/3D Transformations Animations Multiple Column Layout User Interface
If you specify only one value for the border-radius property, this radius will be applied to all 4corners.However, you can specify each corner separately if you wish. Here are the rules: Four values: first value applies to top-left, second value applies to top-right, third value applies to bottom-right, and fourth value applies to bottom-left corner Three values: first value applies to top-left, second value applies to top-right and bottom-left, and third value applies to bottom-right Two values: first value applies to top-left and bottom-right corner, and the second value applies to top-right and bottom-left corner One value: all four corners are rounded equally
Example#rcorners4 { border-radius: 15px 50px 30px 5px; background: #8AC007; padding: 20px; width: 200px; height: 150px;}
#rcorners5 { border-radius: 15px 50px 30px; background: #8AC007; padding: 20px; width: 200px; height: 150px;}
#rcorners6 { border-radius: 15px 50px; background: #8AC007; padding: 20px; width: 200px; height: 150px;}
Property Description
Specifies the amount by which the border image area extends beyondborder-image-outset the border box
CSS3 Backgrounds
CSS3 contains a few new background properties, which allow greater control of the backgroundelement.In this chapter you will learn how to add multiple background images to one element.You will also learn about the following new CSS3 properties:
background-size background-origin background-clip
CSS3 allows you to add multiple background images for an element, through the background-imageproperty.The different background images are separated by commas, and the images are stacked on top of eachother, where the first image is closest to the viewer.The following example has two background images, the first image is a flower (aligned to the bottomand right) and the second image is a paper background (aligned to the top-left corner):
#example1 { background-image: url(img_flwr.gif), url(paper.gif); background-position: right bottom, left top; background-repeat: no-repeat, repeat;}
Multiple background images can be specified using either the individual background properties (asabove) or the background shorthand property.The following example uses the background shorthand property (same result as example above):
#example1 { background: url(img_flwr.gif) right bottom no-repeat, url(paper.gif) left top repeat;}
background A shorthand property for setting all the background properties in one declaration
The CSS3 background-origin property specifies where the background image is positioned.The property takes three different values:
border-box - the background image starts from the upper left corner of the border padding-box - (default) the background image starts from the upper left corner of the padding edge content-box - the background image starts from the upper left corner of the content
The CSS3 background-clip property specifies the painting area of the background.The property takes three different values:
border-box - (default) the background is painted to the outside edge of the border padding-box - the background is painted to the outside edge of the padding content-box - the background is painted within the content box
CSS3 Colors
RGBA colors HSL colors HSLA colors opacity
RGBA Colors
RGBA color values are an extension of RGB color values with an alpha channel - which specifies theopacity for a color.An RGBA color value is specified with: rgba(red, green, blue, alpha). The alpha parameter is anumber between 0.0 (fully transparent) and 1.0 (fully opaque).Example#p1 {background-color: rgba(255, 0, 0, 0.3);} /* red with opacity */
HSL Colors
HSLA Colors
HSLA color values are an extension of HSL color values with an alpha channel - which specifies theopacity for a color.An HSLA color value is specified with: hsla(hue, saturation, lightness, alpha), where the alphaparameter defines the opacity. The alpha parameter is a number between 0.0 (fully transparent) and1.0 (fully opaque).
Example#p1 {background-color: hsla(120, 100%, 50%, 0.3);} /* green with opacity */
Opacity
The CSS3 opacity property sets the opacity for a specified RGB value.The opacity property value must be a number between 0.0 (fully transparent) and 1.0 (fully opaque).
CSS3 Gradients
CSS3 gradients let you display smooth transitions between two or more specified colors.CSS3 gradients you can reduce download time and bandwidth usage. In addition, elements withgradients look better when zoomed, because the gradient is generated by the browser.CSS3 defines two types of gradients: Linear Gradients (goes down/up/left/right/diagonally) Radial Gradients (defined by their center)
To create a linear gradient you must define at least two color stops. Color stops are the colors youwant to render smooth transitions among. You can also set a starting point and a direction (or anangle) along with the gradient effect.Example of Linear Gradient:
Syntax
ExampleA linear gradient from top to bottom: background: linear-gradient(red, blue); /* Standard syntax */A linear gradient from left to right: background: linear-gradient(to right, red , blue);A linear gradient that starts at top left (and goes to bottom right): background: linear-gradient(tobottom right, red , blue); /* Standard syntax */
Property Descriptionbox-shadow Adds one or more shadows to an element
CSS3 2D Transforms
translate() rotate() scale() skewX() skewY() matrix()
The translate() method moves an element from its current position (according to the parameters givenfor the X-axis and the Y-axis).
The rotate() method rotates an element clockwise or counter-clockwise according to a given degree.
The skewX() method skews an element along the X-axis by the given angle.
The skewY() method skews an element along the Y-axis by the given angle.
The skew() method skews an element along the X and Y-axis by the given angles.
T he matrix() Method
The matrix() method combines all the 2D transform methods into one.
Property Descriptiontransform Applies a 2D or 3D transformation to an element
2D Transform Methods
Function Description
translate(x,y) Defines a 2D translation, moving the element along the X- and the Y-axis
scale(x,y) Defines a 2D scale transformation, changing the elements width and height
CSS3 Transitions
CSS3 transitions allows you to change property values smoothly (from one value to another), over agiven duration.Example: Mouse over the element below to see a CSS3 transition effectCSS3 Transition Properties
A shorthand property for setting the four transition properties into a singletransition property
transition-property Specifies the name of the CSS property the transition effect is for
transition-timing- Specifies the speed curve of the transition effectfunction
1. YolaWhat it does: Yola lets you build a basic website by picking a template and filling out a few simpleforms. Once you have a rough outline, you fine-tune your site with an in-place editing tool. Yola hasthe goods to let you really dig into the web. You can integrate your site with an impressive list ofthird-party services such as Google Maps and PayPal, Flickr for photo sharing and Picnik for photoediting.
What it costs: The basic web-building tool and a Yola.com address are free. For extra features,better-looking templates and the ability to use your own domain name, the Yola Silver upgrade is$100 per year.
2. JimdoWhat it does: Jimdo's free version does what a respectable website builder should do, and not muchelse. We suggest springing for the upgrades (which are reasonably priced) to unlock some coolbusiness features, such as custom newsletters to keep in touch with your customers, page-view stats,PayPal stores and password-protected employees-only pages.
What it costs: Basic features and a Jimdo.com address are free. Jimdo Pro is $5 per month. JimdoBusiness is $15 per month, including unlimited data storage and online selling, two domain namesand business-specific site designs.
3. WIXWhat it does: Wix lets you build a great-looking website in no time with its easy-to-use, what-you-see-is-what-you-get editor. Here's the downside: The web development tool is based on Adobe Flash,which works on most PCs but isn't supported by some mobile devices, including the all-powerfulApple iPad. If that isn't a problem for you, Wix has lots of elegant templates that are easy tocustomize and can fit every business need. Wix's image-heavy sites are especially great for photogalleries, which really show clients what your business can do. A new mobile tool lets you build asimple, smartphone-optimized site to reach on-the-go clients.
What it costs: The full-featured website-building tool and Wix.com address are free. Paidsubscriptions, which let you do things like remove ads and link a site to your own domain name, run$5 to $16 per month.
4. Intuit Websites
What it does: Starting a business takes creativity, but maybe you're not the artistic type. Luckily,even the most design-challenged among us can squeeze a respectable-looking website out of Intuit'ssomewhat bland but reliable web-editing tool. A quick survey helps you pick a template that's basedon what your business does and your goals for the website. The template sorter goes into more detailthan many website builders that make you wade through thousands of templates. From there you cantinker with the look and layout, but with some quick text and picture entries you'll be well on yourway to a reasonable web presence.What it costs: The starter package is free for 30 days, then $5 per month. Business and Professionalpackages are $24 and $50 per month, respectively, and include features like custom domain names,online selling tools and search engine optimization. Insider's note: Intuit has several resaleagreements with large telecom companies like Verizon, so don't be afraid to dig around to find apackage discount.
5. Google Sites
What it does: This service can give you a simple Google web presence for free. But you probablydon't need that when there are better, faster and easier options from the likes of Facebook, Twitter andLinkedIn. What Google Sites does best happens outside the public eye. With this tool you can createprivate, team-based websites within your business--which turns that Google Apps account of yoursinto a powerful business organization tool. Google Sites puts nifty collaboration tools likeannouncements, documents and task lists in one online location, allowing you and your colleagues toaccess them from anywhere. It's a great way to bring some sanity to the startup chaos.
Source:http://www.sqa.org.uk/e-learning/ClientSide01CD/index.htmhttp://www.w3schools.com/http://www.entrepreneur.com/article/220447http://www.tutorialspoint.com/javascript/https://www.codeschool.com/paths/javascripthttp://www.htmlandcssbook.comPPT present in internet in regard to the above topics
Books:
1. Harvey Deitel, Abbey Deitel, Internet and World Wide Web: How To Program 5 th Edition.