WT Unit-3
WT Unit-3
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.htmlWelcome 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 - StringNon-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] //1str.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 literalsIntegers 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: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.
stitle> DOM!I!This is the welcome message.
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.This is the welcome message.
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)