0% found this document useful (0 votes)
457 views41 pages

WT Unit-3

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
457 views41 pages

WT Unit-3

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 41
WEB TECHNOLOGIES — UNIT - 2 JavaScript = JavaScript originates from a language called LiveScript. The idea was to find a language which can be used at client side, but not complicated as Java. = JavaScriptis a light weight, interpreted and dynamic programming language = Itallows client-side script to interact with the user and make the dynamic pages = JavaScript can be implemented with javaScript statements that are placed within the HTML tags in a web page. = Itis a case-sensitive language. JavaScript is a simple language which is only suitable for simple tasks. A JavaScript consists of lines of executable computer code = AJavaScript is usually embedded directly into HTML pages = JavaScript is an interpreted language (means that scripts execute without preliminary compilation) Everyone can use JavaScript without purchasing a license = JavaScript is used in millions of Web pages to improve the design, validate forms, detect browsers, create cookies, and much more. = JavaScript is supportable in several operating systems including, Windows, macOS, etc. Are Java and JavaScript similar? * Java and JavaScript are two completely different languages in both concept and design! * Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in the same category as C and C++. Benefits of JavaScript : * Itis widely supported in browser * make the web site dynamic. © Itgives easy access to document object and can manipulate most of them * JavaScript can give interesting animations with many multimedia datatypes. © Special plug-ins are not required to use JavaScript * JavaScript is secure language * JavaScript code resembles the code of C language, The syntax of both the language is very close to each other. The set of tokens and constructs are same in both the language. Implementation of JavaScript: * JavaScript can be implemented using JavaScript statements that are placed within the HTML tags in a web page. * You can place the How to put JavaScript code into a HTML page? JavaScript provides 3 places to put the JavaScript code: > within body tag > within head tag > external JavaScript file. Code between the body tag: Code between the head tag

Welcome to JavaScript

External JavaScript file > It provides code re-usability because single JavaScript file can be used in several html pages. > An external JavaScript file must be saved by .js extension. > It increases the speed of the webpage. Example: message.js function msg(){ alert("Hello Javatpoint"); } index.html

Welcome to JavaScript

Important points about JavaScript: With traditional programming languages, like C++ and Java, each code statement has to end with a semicolon (;) Many programmers continue this habit when writing JavaScript, but in general, semicolons are optional! However, semicolons are required if you want to put more than one statement on a single line. Example: JavaScript program contains variables, objects and functions. Blocks of code must be surrounded by curly brackets. Functions have parameters which are passed inside parenthesis Variables are declared using the keyword var. Script does not require main function and exit condition. JavaScript Comment There are two types of comments in JavaScript. 1.Single-line Comment 2. Multi-line Comment Thus — * Any text between a // and the end ofa line is treated as a comment and is ignored by JavaScript. * Any text between the characters /* and */is treated as a comment. This may span multiple lines. * JavaScript also recognizes the HTML comment opening sequence is not recognized by JavaScript so it should be written as //-->. JavaScript Variables: * Variables are used to store data. * Avariable is a "container" for information you want to store. It is simply a name of storage location. * Avariable's value can change during the script. * You can refer to a variable by name to see its value or to change its value. © There are two types of variables in JavaScript : > local variable . > global variable. Rules of naming JavaScript variables: * They must start with a letter or underscore ("_") * Subsequent characters can also be digits (0-9) or letters (A-Z and/or 2-2). * Remember, JavaScript is case-sensitive. (That means that MyVariable and myVariable are two different names to JavaScript, because they have different capitalization.) * Some examples of legal names are Number_hits, temp99, and _name. JavaScript local variable: A JavaScript local variable is declared inside block or function, It is called a local variable, because it is available only within the function. JavaScript global variable When you declare a variable by assignment outside of a function, itis called a global variable, because it is available everywhere in the current document. A JavaScript global variable is accessible from any function. Variables can store all kinds of data . JavaScript recognizes the following types of values: * Numbers, such as 42 or 3.14159 * Logical (Boolean) values, either true or false Strings, such as "Howdy!" * null, a special keyword which refers to nothing * This relatively small set of types of values, or data types, enables you to perform useful functions with your applications. There is no explicit distinction between integer and real-valued numbers. JavaScript Data Types JavaScript provides different data types to hold different types of values. There are two types of data types in JavaScript: 1 Primitive data type 2.Non-primitive (reference) data type JavaScript is a dynamic type language, means we don't need to specify type of the variable because it is dynamically used by JavaScript engine. Primitive datatypes: 1. Striny : represents sequence of characters e.g. "hello" 2. Number: represents numeric values e.g. 100 3. Boolean: represents boolean value either false or true 4, Undefined: represents undefined value 5, Null: represents null i.e, no value at all JavaScript - String Non-primitive datatypes: 1. Object: represents instance through which we can access members 2. Array: represents group of similar values. 3. RegExp: represents regular expression Data type conversion: JavaScript is a loosely typed language. That means you do not have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution. So, for example, var answer = 42 And later, you could assign the same variable a string value, for example, answer = "Thanks for all the fish..." In expressions involving numeric and string values, JavaScript converts the numeric values to strings. O String String is a primitive data type in JavaScript. It must be enclosed in single or double quotation marks. Example: “Hello World" ‘Hello World’ A string can also be treated like zero index based character array. var str = 'Hello World’; str[0] //H str[1] //e str[2] //1 str.length // 11 Accessing a String String can be accessed using for loop. String-Concatenation String can be concatenated using plus (+) operator in JavaScript. var str = 'Hello' + "World" Include quotation marks inside string Escape characters in JavaScript help inserting special characters in the webpage without breaking the code. We use the backslash (\) character to specify a special character. Notation: V Itadds a single quote in the page \’ Itadds a double quote in the page. \n (Newline) It takes control to the next line on the page. O Number The Number type represents both integer and floating-point numbers and has 3 symbolic values: * +Infinity * -Infinity * NaN (Not-a-Number) Q Boolean The Boolean type represents a logical value that has two possible values: true and false. Q Null The Null datatype in JavaScript only represents nullvalue ( non-existent or invalid object or address ) It means we have defined a variable but have not assigned any value yet, so value is absence. Anull value evaluates to false in conditionalexpression. Q Undefined Undefined is also a primitive value in JavaScript. A variable or an object has an undefined value when no value is assigned before using it. An undefined evaluates to false when used in conditional expression. Normally, we use undefined for checks like seeing if a variable has a value assigned, Literals You use literals to represent values in JavaScript. These are fixed values, not variables, that youliterally provide in your script. Examples of literals include: 1234, "This is a literal," and true. © Integer literals Integers can be expressed in decimal (base 10), hexadecimal (base 16), and octal (base 8). A decimal integer literal consists of a sequence of digits without a leading 0 (zero). A leading 0 (zero) on an integer literal indicates it is in octal; a leading Ox (or OX) indicates hexadecimal. * Floating-point literals A floating-point literal can have the following parts: a decimal integer, a decimal point ("."),a fraction (another decimal number), an exponent, and a type suffix. The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or "-"). A floating-point literal must have at least one digit, plus either a decimal point or "e" (or "E"). Some examples of floating-point literals are 3.1415, -3.1E12, .1e12, and 2E-12 * Boolean literals The Boolean type has two literal values: true and false. © String literals A string literal is zero or more characters enclosed in double (") or single (') quotation marks. A string must be delimited by quotation marks of the same type; that is, either both single quotation marks or double quotation marks. The following are examples of string literals: "blah" Special characters In addition to ordinary characters, you can also include special characters in strings, as shown in the last element in the preceding list. The following table lists the special characters that you can use in JavaScript strings. Character Meaning \b backspace \f form feed \n newline \r carriage return \t tab \\ backslash character Escaping characters A preceding backslash is ignored, with the exception of a quotation mark and the backslash character itself. You can insert quotation marks inside strings by preceding them with a backslash. This is known as escaping the quotation marks CONDITIONAL STATEMENTS: In JavaScript we have the following conditional statements: © if statement - use this statement if you want to execute some code only if a specified condition is true if (condition) { code to be executed if condition is true .else statement - use this statement if you want to execute some code if the condition is true and another code if the condition is false if (condition) { code to be executed if condition is true } else { code to be executed if condition is not true } © if..else ...else statement - use this statement if you want to select one of many blocks of code to be executed if (expression 1) { Statement(s) to be executed if expression 1 is true }else if (expression 2) { Statement(s) to be executed if expression 2 is true }else { Statement(s) to be executed if no expression is true } * switch statement - use this statement if you want to select one of many blocks of code to be executed JAVASCRIPT LOOPS: Loops are handy, if you want to run the same code over and over again, each time with a different value. * for - loops through a block of code a number of times for (statement 1; statement 2; statement 3) { // code block to be executed } © for/in - loops through the properties of an object © while - loops through a block of code while a specified condition is true while (condition) { // code block to be executed } © do/while - also loops through a block of code while a specified condition is true do{ // code block to be executed } while (condition); JAVASCRIPT FUNCTIONS: A JavaScript function is a block of code designed to perform a particular task. Syntax: function name(parameter1, parameter2, parameter3) { // code to be executed } Function Invocation The code inside the function will execute when "something” invokes (calls) the function: * When an event occurs (when a user clicks a button) * When it is invoked (called) from JavaScript code Example: java script programé/title> <script languague="javascript"> function popup() { var major=parseint(navigator.appVersion); var minor=parselnt(navigator.appVersion); var agent=navigator.userAgent.toLowerCase(); document.write(agent+" "+major); window.alert(agent+" " } function farewell() { +major); window.alert(“Welcome to Farewell and thanks for visiting"); } </script> JavaScript Operators * Arithmetic Operators: X++ Operator Description Example Result + Addition x2 4 y=2 xty - Subtraction 3 * Multiplication 20 / Division 15/5 3 5/2 2,5 % Modulus (division | 5%2 1 remainder) [10%8 2 10%2 0 + Increment x5 x=6 _ Decrement x25 x4 x * Assignment Operators Operator Example Is The Same As = xy ey +2 xtsy Xexty = xeKY x x*ay xex*y i x/=y xex/y %= xexhy Comparision Operators Operator Description Example = is equal to 5==8 returns false is equal to (checks for both value and type) =y returns true =y returns false Is is not equal 5158 returns true > is greater than '5>8 returns false < is less than 5<8 returns true >= is greater than or equal | 5>=8 returns false to <= is less than or equalto | 5<=8 returns true © Logical Operators: Operator Description Example BR and x=6 y=3 (x< 10 && y > 1) returns true I or x6 =3 ==5) returns ! not x=6 -y) returns true * Special Operators: Operator (2) New Typeof JAVASCRIPT POP-UP BOXES: JavaScript has three kind of popup boxes: 1. Alert box 2. Confirm box 3. Prompt box Alert Box Description Conditional Operator returns value based on the condition, Itis like if-else. Comma Operator allows multiple expressions to be evaluated as single statement. creates an instance (object) checks the type of object. An alert box is often used if you want to make sure information comes through to the user.When an alert box pops up, the user will have to click "OK" to proceed. <script> alert("Hello World!") </script> Confirm Box Aconfirm box is often used if you want the user to verify or accept something. When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed, If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false. Prompt Box A prompt box is often used if you want the user to input a value before entering a page. When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. If the user clicks "OK", the box returns the input value. If the user clicks "Cancel the box returns null. JAVASCRIPT OBJECTS: * Many times, variables or arrays are not sufficient to simulate real life situations. * JavaScript tries to be an object-oriented language but it’s not really OO language. * JavaScript allows you to create objects that act like real life objects. * Astudent or a home can be an object that have many unique characteristics of their own. * You can create properties and methods to your objects to make programming easier. * Forexample ,If your object is a student, it will have properties like first name, last name, id etc and methods like calculateRank, changeAddress etc. * If your object is a home, it will have properties like number of rooms, paint color, location etc and methods like calculateArea, changeOwner etc. * Objects can have functions as well as variables aliased by giving a unique name. JavaScript is an object-based language. Everything is an object in JavaScript. * A JavaScript object is an entity having state and behavior (properties and method). For example: car, pen, bike, chair, glass, keyboard, monitor etc. The syntax of creating object directly is given below: var objectname=new Object(); new keyword is used to create objects. It allocates memory and storage for them and sets all variables that can be set at this stage. <script> var emp=new Object(); emp.id=101; emp.name="Ravi Malik"; emp.salary=50000; document.write(emp.id+" "+emp.name+" "+emp.salary); </script> Access Object Properties and Methods: You can access properties of an object like this: objectname.propertyname; You can access methods of an object like this: objectname.methodname(); Object Constructor The second way to create an object is with Object Constructor using new keyword. var person = new Object(); // Attach properties and methods to person object person-firstName = "Malige"; person["lastName"] = "Gangappa"; person.getFullName = function () { return this.firstName + '' + this.lastName; i ARRAY OBJECT Arrays in JavaScript are dynamically sized, automatically growing. Arrays can be created in two ways: 1. Array Constructor 2. Array literals Using Constructor: var colors = new Array(); var colors = new Array(10); var colors = new Array(“red”,”green”,”blue”); Using literals: var colors “red”,”green”,”blue”] var names = []; Properties: Here is a list of the properties of the Array object along with their description. * constructor: Returns a reference to the array function that created the object. * index: The property represents the zero-based index of the match in the string * input: This property is only present in arrays created by regular expression matches. © length: Reflects the number of elements in an array Array Methods: Here is a list of the methods of the Array object along with their description. © concat() : Returns a new array comprised of this array joined with other array(s) and/or value(s). Syntax : array.concat(array2[,array3 [,...arrayn) * pop() :Removes the last element from an array and returns that element. * push() :Adds one or more elements to the end of an array and returns the new length of the array * indexOf(element,start) : Returns the first index of an element within an array equal to the specified value, or -1 if none is found. * join(string): array join() method joins all the elements of an array into a string. Syntax: array.join(separator); © reverse() :Return the original array elements in reverse order. * shift() : removes the first element from an array and returns that element * sort() ‘The JavaScript array sort() method is used to arrange the array elements in some order. By default, sort() method follows the ascending order. © slice(): TheJavaScriptarray slice() method extracts the partof the given array and returns it. This method doesn't change the original array. Syntax: array.slice(start,end) STRING OBJECT The JavaScript string is an object that represents a sequence of characters. String object wraps JavaScript's string primitive data type with a number of helper methods. There are 2 ways to create string in JavaScript 1.By string literal 2.By string object (using new keyword) By string literal var stringName = "string value"; By string object (using new keyword) var stringname=new String("string literal"); Methods charAt(x): Returns the character at the "x" position within the string. concat(vl, v2,...): Combines one or more strings (arguments v |,v2 etc) into the existing one and returns the combined string. Original string is not modified. Syntax : string.concat(str1,str2,...,strn) indexOf() : Searches and (if found) returns the index number of the searched character or substring within the string. If not found, -1 is returned. “Start” is an optional argument specifying the position within string to begin the search. match(regexp) : regexp - It represents the regular expression which is to be searched. Returns the matched regular expression. split(delimiter, [limit]) : is used to split the given string into array of strings by separating it into substrings using a specified separator provided in the argument. Example: str.split(separator, limit) toLowerCase() toUpperCase() Regular Expression Object: A regular expression is an object that describes a pattern of characters. © The JavaScript RegExp class represents regular expressions, and both String and RegExp define methods that use regular expressions to perform powerful pattern-matching and search-and-replace functions on text. Syntax: A regular expression could be defined with the RegExp () constructor, as follows — var pattern =new RegExp(pattern, attributes); or simply var pattern =/pattern/attributes; Description of the parameters - * pattern — A string that specifies the pattern of the regular expression or another regular expression. * attributes - An optional string containing any of the "g", "i", and "m" attributes that specify global, case-insensitive, and multiline matches, respectively. Methods: * exec(): The exec method searches string for text that matches RegExp. If it finds a match,it returns an array of results; otherw ise,it returns null. Syntax: RegExpObje ct .exec( string ); * match () : Takes a regular expression as a parameter and returns an array of all the matching string found in the string under consideration . If no matches are found ,then it returns false. Syntax: string.match( regexp ) * test(): test() method tests fora match ina string. This method returns true if it finds a match, otherwise it returns false. Syntax: RegExpObject .test(string) Date Object: The Date object is a datatype built into the JavaScript language. Date objects are created with the new Date( ) as shown below. Once Date objects created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time. You can display a timer on the webpage with the help of JavaScript date object. Syntax: You can use any of the following syntaxes to create a Date object using Date() constructor. new Date( ) new Date(milliseconds) new Date(datestring) new Date(year,month,date[,hour,minute,second, millisecond ]) Create a new Date object: var d = new Date(); Date Methods: Date():Returns today's date and time getDate():Returns the day of the month for the specified date according to local time. getDay():Returns the day of the week for the specified date according to local time. getFullYear():Returns the year of the specified date according to local time. getHours():Returns the hour in the specified date according to local time. getMilliseconds():Returns the milliseconds in the specified date according to local time. getMinutes():Returns the minutes in the specified date according to local time. getMonth():Returns the month in the specified date according to local time. * getSeconds():Returns the seconds in the specified date according to local time. © getTime():Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. Set Methods: © setDate() - set the day as number(1-31) * setFullYear() - set the year(optionally month and day) * setHours() - set the hour(0-23) Math Object: * The math object provides you properties and methods for mathematical constants and functions. * Unlike other global objects, Math is not a constructor. * All the properties and methods of Math are static and can be called by using Math as an object without creating it. * Thus, you refer to the constant pias Math.Pl and you call the sine function as Math.sin(x), where x is the method's argument. Syntax: The syntax to call the properties and methods of Math are as follows var pi_val = Math.Pl; var sine_val = Math.sin(30); Methods: 1. abs():Returns the arctangent of the quotient of its arguments. 2. ceil():Returns the smallest integer greater than or equal to a number. 3. cos():Returns the cosine of a number. 4. exp():Returns EN, where Nis the argument, and E is Euler's constant, the base of the natural logarithm. 5. floor():Returns the largest integer less than or equal to a number. 6. _log():Returns the natural logarithm (base E) of a number. 7. min():Returns the smallest of zero or more numbers. 8. pow():Returns base to the exponent power, that is, base exponent. 9. random():Returns a pseudo-random number between 0 and 1. Number Object: * The JavaScript number object enables you to represent a numeric value. It may be integer or floating-point. * You can create number object as shown below: var n = new Number(value); * If value can't be converted to number, it returns NaN( Not a Number) that can be chec ked by isNaN() method. * NaN is a value which represent something which is not a number. Properties: Property Description The smallest interval between two representable numbers Returns the maximum possible safe Number.MAX_SAFE_INTEGER integer value in JavaScript which is 253 -1 Returns the largest positive representable number Returns the minimum possible safe Number.MIN_SAFE_INTEGER integer value in JavaScript which is - (253-1) Return the minimum representable numerical value possible in JavaScript. Number.EPSILON Number.MAX_VALUE Number.MIN_VALUE It represents the special "Not a Number.NaN umber.Na Number" value Number.NEGATIVE_INFINITY It represents the value of Negative Infinity. Number.POSITIVE_INFINITY Number. prototype Methods: It represents the value of Negative Infinity. This can be used to add more properties to the Number object Method name Description Number.isNaN() Static method; used to check whether the given value is NaN or not. Number. isFinite() Static method; used to check whether the given value isa finite number or not. Number .isinteger() Static method; used to check whether the given value is an integer number or not. Number isSafeinteger() Static method; used to check if the given value is a safe value or not, i.e. between 253 - 1 to -(253 - 1) Number.parseFloat(string) Static method; used to convert a string to a floating-point number. Number.parseint(string, [radix] Static method; used to convert a string to an integer. Here radix represents the base in mathematical numeral systems. Returns the primitive value of the valuef() Number object. Returns a String value of number toString() object 6 toFbed(e) Rounds up a number to x digits after the decimal. toPrecision(x) Rounds up a number to a length of x digits. toExponential(x) Converts a number into an Exponential notation. eval() Function The keyword eval is an abbreviation for “evaluate.” The function essentially takes a string with JavaScript code The eval() method is not suggested to use in JavaScript since it executes slower . Window Object: * The default object of browser is window. The window object represents a window in browser. window .open("URL", "WindowName" “f eaturel, f eaturen) Properties: status menubar Scrollbars resizable Width Height Methods: Alert() - displays the alert box containing the message with OK button Confirm() - dispalys the confirm dialogue box containing message with Ok and Cancel buttons Prompt() - displays a dialogue box to get input from the user. Open() - opens a new window Close() - closes the current window Block level scoping JavaScript does not support block-level scoping. A variable defined within a block, for instance an if- or a for-statement, will exist even after the block finishes execution. © It will be available until the function in which the variable is declared finishes. function noBlock(){ if(true) { var width = 10; // not block level scoped } alert(width); // variable num is available outside the if block } noBlock (); // => 10 EXAMPLES: 1. y=20x+12, where x=3 Display Y in alert box? <script> x53 y=20*x+12 alert(y) </script> 2. Sum of two numbers <script> sl=12 s2=28 total=s1+s2 document.write(“Sum of s1 and s2 is: "+total) </script> 3, s1=12, s2=28. Perform arithmetic operations on S1 and s2 and display result <script> s1=12 s2=28 total=s1+s2 sub=s1-s2 mulss1*s2 div=st/s2 document.write("<br>addition value is: "+total) document.write("<br>subtraction value is: "+sub) document.write("<br>Multiplication value is: "+mul) document write("<br>division of s1 by 2 is "+div) </script> DHTML AND DOCUMENT OBJECT MODEL: © JavaScriptcan access all the elements in a webpage making use of Document Object Model (DOM). In fact, the web browser creates a DOM of the webpage when the page is loaded, The DOM model is created as a tree of objects like this: Root element, <himb> —_I—__ Element Element <head> <body> —lL—__ Element, Element <b> <p> Text Text “My Header” “My Paragraph" BENEFITS OF DHTML: Using DOM, JavaScript can perform multiple tasks. It can create new elements and attributes. It can change the existing elements and attributes and Even it can remove existing elements and attributes. JavaScript can also react to existing events and create new events in the page. JavaScript can change all the CSS styles in the page JavaScript can create new HTML events in the page The DOM is a W3C (World Wide Web Consortium) standard. The DOM defines a standard for accessing documents: "The W3C Document Object Model (DOM) is a platform and language- neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.” The W3C DOM standard is separated into 3 different parts: * Core DOM - standard model for all document types * XMLDOM.- standard model for XML documents * HTMLDOM- standard model for HTML documents * The document object represents the whole html document . * When html document is loaded in the browser, it becomes a document object. It is the root element that represents the htm! document. * By the help of document object, we can add dynamic content to our web page. window.document Issame as( document) * The HTML DOM can be accessed with JavaScript (and with other programming languages). * Inthe DOM, all HTML elements are defined as objects. * The programming interface is the properties and methods of each object. * Aproperty isa value that you can get or set (like changing the content of an HTML element). * Amethod is an action you can do (like add or deleting an HTML element). METHODS OF DOM: Method Description write("string") writes the given string on the doucment. writeln("string") writes the given string on the doucment with newline character at the end. getElementByld() returns the element having the given id value. getElementsByName() returns all the elements having the given name value. getElementsByTagName() returns all the elements having the given tag name. getElementsByClassName() returns all the elements having the given class name. COMMON METHODS AND PROPERTIES: getElementByld: To access elements and attributes whose id is set. innerHTML: To access the content of an element. <html> <head> stitle> DOM!I!

Welcome

This is the welcome message.

Technology

This is the technology section.

getElementsByTagName: To access elements and attributes using tag name. This method will return an array of all the items with the same tag name. DOMI!!

Welcome

This is the welcome message.

Technology

This is the technology section.

createElement: To create new element removeChild: Remove an element You can add an event handler to a particular element like this: document getElementByld{id).onclick=function() { lines of code to be executed } OR document getElementByld(id).addEventListener("click", functionname) DOM!!! Data validation HTML form validation can be done by JavaScript. Reading data from HTML element var x= document.forms["myForm'"].[“element_name'].value; We can use document.form1.name.value to get the input given by the user. Example:
Example:
Enter No:
EVENTS. Q JavaScript's interaction with HTML is handled through events that occur when the user or the browser manipulates a page. Q Events are a part of the Document Object Model (DOM) O Every HTML element contains a set of events which can trigger JavaScript Code. Examples of events > An HTML web page has finished loading > An HTML input field was changed >An HTML button was clicked Event Types: > Mouse-related: mouse movement, button click, enter/leave element > Keyboard-related: down, up, press Input field events :Input field changed, Form submitted > Miscellaneous: v Page loaded/unloaded v Image loaded Vv Uncaught exception Filters and transitions Play vital role in giving the visual effect to web pages. CSS filters are used to set visual effects to text, images, and other aspects of a webpage. CSS Syntax filter: none | invert() | drop- shadow() | brightness() | saturate() | blur() | grayscale() | url(); The style of the text or image can be set using filter attribute. We can use various functions such as blur(),shadow() and grayscale() to give text effects. Example Program : Create a multiplication table asking the user the number of rows and columns he wants. Multiplication Table

You might also like