Full Transcript

UNIT-II CHAPTER -1 JAVASCRIPT CONTENTS 1. Introduction 2. Variables 3. Arrays 4. Functions 5. Javascript Objects 6. Event Handling 7. DOM 8. Form Validation 9. References ...

UNIT-II CHAPTER -1 JAVASCRIPT CONTENTS 1. Introduction 2. Variables 3. Arrays 4. Functions 5. Javascript Objects 6. Event Handling 7. DOM 8. Form Validation 9. References 1. INTRODUCTION JavaScript is a programming language initially designed to interact with elements of web pages. JavaScript is used with HTML and CSS to enhance a web page’s functionality, such as validating forms, creating interactive maps, and displaying animated charts. When a web page is loaded, i.e., after HTML and CSS have been downloaded, the JavaScript engine in the web browser executes the JavaScript code. The JavaScript code then modifies the HTML and CSS to update the user interface dynamically. What is Javascript engine? The JavaScript engine is a component of web browsers responsible for interpreting and executing JavaScript code. It includes a parser to analyze the code, a compiler to convert it into machine code, and an interpreter to run the compiled code. Examples: V8 in Chrome, SpiderMonkey in Firefox, and JavaScriptCore in Safari First Javascript program: JavaScript in Body document.getElementById("demo").innerHTML = "My First JavaScript"; How to include Javascript into HTML page? There are three ways to include javascript into HTML page 1. Add in 2. Add in The tag notifies the browser that everything contained within is script and is to be interpreted by a suitable interpreter. Javascript code 3. External javascript file - Scripts can be placed in external files - Javascript file has the extension.js. - It does not contain tags. - To use external script, put the name of the script file in src attribute of tag Advantages of external javascript file:  It separates HTML and script code  It makes HTML and script easier to read and maintain  External files are cached by the some browsers and can speed up page loading  Javascript code remains hidden if the browser is not compatible with it where as incompatible embedded Javascript is displayed as normal text. External script can be referenced in 3 ways:  With full URL  With a file path  With file name without path Comments in Javascript code:  Line comment // this is comment line  Block comment If a javascript code is embedded in the HTML file and a browser is incompatible with the scripting language, the script code will get displayed on the page as normal text. To avoid this, HTML comment can be used to hide the script. Ex: 2. VARIABLES  Variables are used to store data.  In Javascript, variables are un-typed.  Variables can be declared in block, function and global scope  Javascript variables can be declared in 4 ways: o Automatically – variables declared without any keyword o Using var o Using let o Using const var – Variables declared with var keyword always have global scope and can be redeclared. let- Variables declared with let keyword have block scope and cannot be redeclared. const – Variables declared with const keyword have block scope and cannot be redeclared or reassigned. Binds Scope Redeclare Reassign Hoisted this var No Yes Yes Yes Yes let Yes No Yes No No const Yes No No No No An undefined variable is a variable that has been declared but not initialized while an undeclared variable is a variable that has not been declared. When to Use var, let, or const? 1. Always declare variables 2. Always use const if the value should not be changed 3. Always use const if the type should not be changed (Arrays and Objects) 4. Only use let if you can't use const 5. Only use var if you MUST support old browsers. 3. ARRAYS  In Javascript, arrays can contain heterogeneous items.  Javascript arrays are also called as associative arrays.  The array index starts with 0. Ex: let colors=[‘red’,’green’,’yellow’,’blue’,’orange’]; let employee=[“Meena”,24,1,25000.00];  Javascript arrays are dynamic in nature. Elements can be added and deleted as and when required. Ex: let num=[1,2,3,4]; num=5; Creating Arrays: Javascript provides constructors to create arrays. There are three versions of array constructors:  Array(); - creates an empty array,i.e. array of length zero o let colors = new Array();  Array(number of elements); o let colors = new Array(5);  Array(comma separated list of elements); o let colors = new Array(‘red’,’green’,’blue’); let colors = new Array(); - creates an empty array, i.e. array of length zero. Elements can be added to the empty array later. colors=’red’; ‘red’ is third element in the array, still first and second elements are undefined. Elements in the array will be colors=(undefined, undefined, ’red’); Javascript array length: To find out the length of array in javascript, use the property length Ex: let colors=[‘red’,’blue’,’gree’,’white’,’black’]; colors.length will return the value 5, as there are 5 items in the array. Array Methods: Method Description toString() Converts array to a string of comma separated array values at(index i) Returns the array element at index i join() Converts array to a string with specified separator pop() Removes last element from array push() Adds new element to the end of the array shift() Removes first element from array and shifts all elements to a lower index unshift() Adds new element at the beginning of array and shifts all elements to one index greater delete(index i) Removes element from index i and leaves it undefined in the array concat(array2) Creates new array merging two arrays 4. FUNCTIONS A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Syntax: function name(arg1,arg2){ //code to be executed return(result); // not for all functions } Function Invocation: A Javascript function can be invoked in any of below ways:  When an event occurs (when a user clicks a button)  When it is invoked (called) from JavaScript code  Automatically (self invoked) 5. Javascript Objects An object is a collection of related properties and methods. Syntax: objectName={property1:value1,property2:value2}; Ex: student={ name:’Madhavi’, rollno:201,branch:’EEE’};  Once the object is created, properties can be accessed using(.) operator let sname = student.name;  A property can be added to the object after the creation student.CGPA=9.6; for/in: for loop can be used to iterate properties of an object Constructor functions: A class in javascript is defined by a function. Objects can be created with the help of the constructor function and the new operator. Ex: function Student(){ } st1=Student(); An object st1 is created and properties can be added now. st1.name=‘Madhavi’; st1.rollNo=501; st1.branch=‘CSE’; this keyword: this keyword is used to refer the newly created object which is passed to the constructor. this keyword can be used to access the object’s properties and methods. Ex: function Student(name, rollno){ this.name=name; this.rollno = rollno; } st1 = new Student(“Madhavi”,501); function Student(name,rollno){ this.name=name; this.rollno=rollno; this.branch='CSE'; } let st={name:'Madhavi',rollno:201,branch:"EEE"}; st1= new Student('Rama',501); for(i in st1){ console.log(i+"="+st1[i]); } Adding new method to object: Methods can be added to the added to the javascript objects. To add methods, there are two steps: 1. Define a method 2. Associate it within the constructor during object creation or make this association later Ex: function getName(){ return this.name; } function Student(name, rollno){ this.name=name; this.rollno = rollno; this.printName=getName(); } st1 = new Student(“Madhavi”,501); var name=st1.printName(); There are built-in objects in javascript. Few of them are: Date String Math Random JSON Parsing and Serialization: To convert JSON data into a JavaScript object, use JSON.parse() method. It parses a valid JSON string into a JavaScript object. Syntax: let jsObject = JSON.parse(jsonStr);  To convert a JavaScript object into JSON data, use the JSON.stringify() method. Syntax: String jsonString = JSON.Stringify(jsObject); const jsonStr='{"name":"Radha","rollno":501,"branch":"CSE"}'; const jsObject = JSON.parse(jsonStr); document.getElementById("pId").innerHTML=jsObject.name; const jsObject={name:"Radha",rollno:501,branch:"CSE"}; const jsonString = JSON.Stringify(jsObject); document.getElementById("pId").innerHTML=jsonString; Javascript Object Hierarchy: Accessing Objects: Javascript objects have container-to-contained relationship, but not class- and-subclass relationships. The top level object is window. Any other object can be referenced by its names, prefixed by the names of all the objects that contain it, in order, separated by (.). Ex: window.document.form Window Object: The window object is the top level object in the object hierarchy. It represents the entire browser window. Few Properties of Window Object: Property Description closed Returns a Boolean value that indicates whether the window has been closed or not document Document currently being displayed in the context window event Keeps track of various events that occur on the page frames Array of frame objects this window contains history Object that contains information about the URLs visited within that window so far length Returns the number of frames contained in this window location Object that contains information on the current URL Few Methods of Window Object: Property Description alert(msg) Displays a dialog box with a specified message and an OK button blur Removes focus from this window close() Closes the window confirm(msg) Displays a dialog box with the specified message and OK and Cancel button prompt(msg,[input]) Displays a dialog box with a message and an input field. Returns the data supplied by the visitor stop() Stops the current download focus() Gives focus to this window 6. Event Handling The procedure of performing action by executing some piece of code when an event is triggered is called event handling. Events: The set of tasks that users may perform on a web page are called interactive events or simply events. Ex: clicking a button, mouse click, moving mouse pointer on a hyperlink, keystroke etc. There are few events which are not interactive, for example, load. For each element of a web page, users may perform a specific set of tasks. Ex: select task cannot be performed on button List of few Javascript events: Event Source click Button, checkbox, radio, link, reset, text, submit, textarea, body focus Select, text, textarea blur Checkbox, radio, select, text, textarea change Select, text, textarea mouseOver Link, text,button,textarea,radio mouseOut Link, text,button,textarea,radio select text, textarea submit form keypress Document, image, link, textarea dblClick Document, image, link, textarea resize window reset form Event Handler: The Javascript code that performs or takes an action when event occurs is called event handler. In Javascript, the handler is usually provided as a function. How an event is handled in Javascript? The handler is associated with event and source waits for an event to occur. When an event occurs, javascript identifies it and executes its handler. Event works as a trigger and the handler is triggered by the event. The handler of the event for some element is specified by assigning it to the property of the element. The property name for the event will be in the form: onclick. Ex: Event Object: In Javascript, an event is represented as a global object called event object. The event object is available only when an event occurs. So, only event handlers can access this event object. Properties of Event Objects: srcElement type altKey altLeft CtrlKey ctrlleft button keycode clientX clientY Event Propagation Model: Event propagation is a way of defining the element order when an event occurs W3C Event Propagation Model  According to W3C specification, an event handling mechanism has two phases: o Event Capturing o Event Bubbling  They always occur in the order specified.  For each of these phases, a separate handler may be registered. In default, handlers are registered for bubbling. Ex: pClick() is executed first and then divClick(). How to register an event for Capturing phase? W3C has provided a method addEventListener() on an element which can be used to register for both capturing and bubbling phases Syntax: element.addEventListener(‘eventname’,eventhandler,flag); eventname - name of the event to be handled eventhandler- handler registered on the element flag – true for capturing phase, false for bubbling phase To cancel the bubble phase, set the below property: event.cancelBubble = true; 7. Document Object Model (DOM) HTML DOM is hierarchical representation of HTML documents. It represents structure and properties of elements on a webpage. The HTML DOM tree corresponding to an HTML document consists of a set of nodes, each of which represents some part of the HTML document. When a web page is loaded, the browser creates a Document Object Model of the page. Browsers traverse the DOM tree and render the document on the screen. All elements, their attributes and their containing text may be accessed through the DOM tree using the interfaces provided in the HTML DOM specification. Javascript also provides a mechanism to navigate and manipulate the HTML DOM tree and so it gets all the power it needs to create dynamic HTML:  JavaScript can change all the HTML elements in the page  JavaScript can change all the HTML attributes in the page  JavaScript can change all the CSS styles in the page  JavaScript can remove existing HTML elements and attributes  JavaScript can add new HTML elements and attributes  JavaScript can react to all existing HTML events in the page  JavaScript can create new HTML events in the page The HTML DOM Tree of Objects Why is DOM required? HTML is used to structure the web pages and Javascript is used to add behavior to our web pages. When an HTML file is loaded into the browser, the JavaScript cannot understand the HTML document directly. So it interprets and interacts with the Document Object Model (DOM), which is created by the browser based on the HTML document. JavaScript can not understand the tags(H) in HTML document but can understand object h1 in DOM. JavaScript interprets DOM easily, using it as a bridge to access and manipulate the elements. DOM Javascript allow access to each of the objects (h1, p, etc) by using different functions. The Document Object Model (DOM) is essential in web development for several reasons:  Dynamic web pages  Interactivity  Content Updates  Cross-Browser Compatibility  Single Page Applications In DOM, every object is a Node. It has the method hasChildNodes(), which can be used to check whether it has any child nodes or not. this is div alert("Does Body have child elements?"+document.body.hasChildNodes()); alert("Does div have child elements?"+document.body.firstChild.hasChildNodes()); document.body.hasChildNodes() returns true where as document.body.firstChild.hasChildNodes() returns false. Navigating DOM tree: The Javascript HTML DOM interface provides facilities to access some elements in an HTML page.  getElementById()  getElementsByName()  getElementsByTagName()  getElementsByClassName() Changing HTML elements: Property Description element.innerHTML = new html Change the inner HTML of an element content element.attribute = new value Change the attribute value of an HTML element element.style.property = new style Change the style of an HTML element Method Description element.setAttribute(attribute, Change the attribute value of an HTML value) element Adding and Deleting Elements: Method Description document.createElement(element) Create an HTML element document.removeChild(element) Remove an HTML element document.appendChild(element) Add an HTML element document.replaceChild(new, old) Replace an HTML element document.write(text) Write into the HTML output stream Adding Event Handlers: document.getElementById(id).onclick = function(){code} 8. Form Validation with Regular Expression A regular expression is a sequence of characters that forms a search pattern. The search pattern can be used for text search and text replace operations. Ex: pattern = /[a-z]*/ test() /world/.test(“Hello World”) exec() /world/.exec(“Hello World”) 9. References 1. TB2: Uttam K. Roy, Web Technologies, OXFORD University press, 2010. 2. https://www.javascripttutorial.net/ 3. https://javascript.info/ 4. https://www.w3schools.com/Js/js_intro.asp 5. https://www.geeksforgeeks.org/dom-document-object-model/

Use Quizgecko on...
Browser
Browser