JavaScript.pdf - 15IT304J Web Programming Unit 2 \u2013 Java Script Introduction \u2022 JavaScript is one of the 3 languages all web developers must learn 1

JavaScript.pdf - 15IT304J Web Programming Unit 2 – Java...

This preview shows page 1 out of 43 pages.

You've reached the end of your free preview.

Want to read all 43 pages?

Unformatted text preview: 15IT304J - Web Programming Unit 2 – Java Script Introduction • JavaScript is one of the 3 languages all web developers must learn: 1. HTML to define the content of web pages 2. CSS to specify the layout of web pages 3. JavaScript to program the behavior of web pages ▪ Power of Java Script: • JavaScript Can Change HTML Content • JavaScript Can Change HTML Attributes • JavaScript Can Change HTML Styles (CSS) • JavaScript Can Validate Data Where Exist: JavaScript • JavaScript can be placed in the <body> and the <head> sections of an HTML page. The <script> Tag • Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both. • In HTML, JavaScript code must be inserted between <script> and </script> tags. • Older examples may use a type attribute: <script type="text/javascript“ • The type attribute is not required. • JavaScript is the default scripting language in HTML. • You can place any number of scripts in an HTML document. JavaScript Functions and Events • A JavaScript function is a block of JavaScript code, that can be executed when "asked" for. • For example, a function can be executed when an event occurs, like when the user clicks a button. • JavaScript in <head> • JavaScript in <body> External JavaScript ❑ It is a good idea to place scripts at the bottom of the <body> element. ❑ JavaScript files have the file extension .js. ❑ Cached JavaScript files can speed up page loads. • Client side scripting language. • Making web pages more dynamic, interactive • JavaScript is a browser-based scripting language developed by Netscape and implemented in all major browsers. • All major web browsers contain JavaScript interpreters, which process the commands written in JavaScript. JavaScript Outputs • JavaScript can "display" the output data in different ways: • Writing into an alert box, using window.alert(). • Writing into the HTML output using document.write(). • Writing into an HTML element, using innerHTML. • Writing into the browser console, using console.log() <script> window.alert(5 + 6); </script> <script> document.write(5 + 6); </script> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = 5 + 6; </script> • Sample Code JavaScript Syntax: • JavaScript is a programming language. • JavaScript statements are separated by semicolon. • In HTML, JavaScript programs can be executed by the web browse • JavaScript is Case Sensitive • JavaScript Statements • JavaScript statements are composed of: Values, Operators, Expressions, Keywords, and Comments. • JavaScript Values • JavaScript syntax defines two types of values: Fixed values and variable values. • Fixed values are called literals. Variable values are called variables. • Number->5.2 • String-> “ hi” JavaScript Variables and Data types Variables : Variables are containers for storing data values. The value of a variable can change throughout the program. Use the var keyword to declare a variable. var x = 10; The term data type refers to the types of values with which a program can work. JavaScript variables can hold many data types, such as numbers, strings, arrays, and more. JavaScript does not define different types of numbers, like integers, short, long, floating-point, etc. JavaScript numbers can be written with or without decimals. JavaScript strings are used for storing and manipulating text. A string can be any text that appears within quotes. You can use single or double quotes. var name = 'John'; var text = "My name is John Smith"; In JavaScript Boolean, you can have one of two values, either true or false. var isActive = true; ExampleCode: JavaScript Control Structure In cases when you need to test for multiple conditions, writing if else statements for each condition might not be the best solution. The switch statement is used to perform different actions based on different conditions. Syntax: switch (expression) { case n1: statements break; default: statements } ExampleCode: JavaScript Looping Statements JavaScript has three types of loops: for, while, and do while. The for syntax for: for (statement 1; statement 2; statement 3) { //code block to be executed } Example: for (; i < 10; ) { document.write(i); i++; } .The while loop repeats through a block of code, as long as a specified condition is true. Syntax: while (condition) { code block } JavaScript Looping Statements The Do...While Loop The for syntax : do { code block } while (condition); Syntax: while (condition) { code block } JavaScript Functions • A JavaScript function is a block of code designed to perform a particular task. Use the same code many times with different arguments, to produce different results. A JavaScript function is executed when "something" invokes, or calls, it. Syntax: function name() { //code to be executed } JavaScript Dialog Functions • JavaScript offers three types of popup boxes, the Alert, Prompt, and Confirm boxes. • Alert Box : An alert box is used when you want to ensure that information gets through to the user. The alert function takes a single parameter, which is the text displayed in the popup box. Example: alert("Do you really want to leave this page?"); • Prompt Box: A prompt box is often used to have the user input a value before entering a page. The prompt() method takes two parameters. - The first is the label, which you want to display in the text box. - The second is a default string to display in the text box (optional). Example: var user = prompt("Please enter your name"); JavaScript Dialog Functions • Confirm Box : A confirm box is often used to have the user verify or accept something. var result = confirm("Do you really want to leave this page?"); if (result == true) { alert("Thanks for visiting"); } else { alert("Thanks for staying with us"); } JavaScript Arrays Arrays store multiple values in a single variable. JavaScript supports arrays of heterogeneous type and dynamic sizing. Declaration of an Array There are basically two ways to declare an array. Example: var student = [ ]; var Student = new Array(); Initialization of an Array & Adding Elements: 1st Method var student =[‘a’,’b’,’c’]; student[student.length]=‘d’; 2nd Method var student =new Array(1,2,3,4); student.push(5); 3rd Method: student.unshift(6); JavaScript Arrays Removing Elements: 1st Method var student =[‘a’,’b’,’c’]; student.pop(); 2nd Method var student =new Array(1,2,3,4); student.shift(); Adding and Removing: var student =new Array(1,2,3,4); student.splice(1,2,5,6,7); //1st parameter is starting position, 2nd number of elements, optional elements to be added JavaScript Arrays Methods Array.Every(); Array.every() function is used when you need to validate each element of a given array. Array.every() accepts a callback function as argument which is called for each element of the array. Example: var stud=[45,78,54,67,34,98]; function fngreaterthan50_every(arr,n) { return arr.every(function(element){ return (element>n);}); } window.alert(fngreaterthan50_every(stud,30)); //the above function process every element and return true if all the elements of array are greater than n. JavaScript Arrays Methods Array.some(); The Array.some() function is used when you need to check if at least one element of a given array passes the test implemented by the callback function. Array.every() accepts a callback function as argument which is called for each element of the array. Example: var stud=[45,78,54,67,34,98]; function fngreaterthan50_some(arr,n) { return arr.some(function(element){ return (element>n);}); } window.alert(fngreaterthan50_some(stud,100)); //the above function process every element and return true if any of the elements of array are greater than n. JavaScript Arrays Methods Array.filter (); Array.prototype.filter() is used to get a new array which has only those array elements which pass the test implemented by the callback function. Array.filter() accepts a callback function as argument which is called for each element of the array. Example: function fnstud_filter(arr) { return arr.filter(function(elements){ return elements>50; }); } window.alert(fnstud_filter(stud)); //return an integer that is sum of all elements in array JavaScript Arrays Methods Array.reduce(); Array.prototype.reduce() function is used when the programmer needs to iterate over a JavaScript array and reduce it to a single value. Array.reduce() accepts a callback function as argument which is called for each element of the array. Example: function reducefun(pre,cur,index,stu) { return pre+cur; } window.alert(stud.reduce(reducefun)); window.alert(fnstud_filter(stud//return an array that has value greater than 50. JavaScript Arrays Methods Array.concat Example: var arr1 = [1,2,3,4]; var arr2 = [5,6,7,8]; var arr3 = arr1.concat(arr2); console.log(arr3); // Output : [1, 2, 3, 4, 5, 6, 7, 8] Arrays.sort() var arr = [3, 1, 5, 4, 2].sort(); console.log(arr); Array.reverse() var arr = [1,2,3,4,5,6,7,8,9,10]; arr.reverse(); console.log(arr); JavaScript Arrays Methods Array.join Example: var arr1 = [1,2,3,4]; document.write(arr1.join(‘|’)); // Output : 1| 2|3| 4 Arrays.fill() var arr = [3, 1, 5, 4, 2] arr.fill(45,3,5); //Output: 3,1,5,45,45,45 Array.find() function isOdd(element, index, array) { return (element%2 == 1); } print([4, 6, 8, 12].find(isOdd)); JavaScript Arrays Arrays store multiple values in a single variable. Example: Creating Array: var courses = new Array("HTML", "CSS", "JS”); var course = courses[0]; // HTML courses[1] = "C++"; //Changes the second element var courses = new Array(3); courses[0] = "HTML"; courses[1] = "CSS"; courses[2] = "JS"; var courses = ["HTML", "CSS", "JS"]; . Array Methods: document.write(courses.length);. var c2 = ["JS", "C++"]; var courses = c1.concat(c2); JavaScript Associate Arrays While many programming languages support arrays with named indexes (text instead of numbers), called associative arrays, JavaScript does not. However, you still can use the named array syntax, which will produce an object. Example: var person = ; //empty array person["name"] = "John"; person["age"] = 46; document.write(person["age"]); //Outputs "46" JavaScript Math & Date Object The Math object allows you to perform mathematical tasks, and includes several properties. document.write(Math.PI) Example: abs,acos,exp,ceil,floor,log,max,min,pow, sqrt,random,round setInterval :The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds). function myAlert() { alert("Hi"); } setInterval(myAlert, 3000); The Date Object: The Date object enables us to work with dates. A date consists of a year, a month, a day, an hour, a minute, a second, and milliseconds var d1 = new Date(86400000); var d2 = new Date("January 2, 2015 10:42:00"); var d3 = new Date(88,5,11,11,42,0,0); GetFullYear, getDay,getMonth,getDate,getHours,getMinute JavaScript Objects Object : JavaScript variables are containers for data values. Objects are variables too, but they can contain many values. Example:. var person = { name: "John", age: 31, favColor: "green", height: 183 }; Object Properties : You can access object properties in two ways. objectName.propertyName //or objectName['propertyName'] JavaScript's built-in length property is used to count the number of characters in a property or string. var course = {name: "JS", lessons: 41}; document.write(course.name.length); JavaScript Objects with methods Object : JavaScript variables are containers for data values. Objects are variables too, but they can contain many values. Example:. var person = { name: "John", age: 31, favColor: "green", height: 183 detials: function(){ return this.name+” “+this.age+ “ “ +this.favColor+” “+this.height; } }; JavaScript Objects with Constructors function Person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; } var Student=new Person(“karthik”,”Raj”,21,”blue”); JavaScript adding new Properties & methods to Objects function Person(first, last, age, eyecolor) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eyecolor; } Person.prototype.nationality = "English"; Person.prototype.name = function() { return this.firstName + " " + this.lastName; } Dom Events Document Object Model of that page, which is an object oriented model of its logical structure. The DOM of an HTML document can be represented as a nested set of boxes: Accessing the HTML Elements: //find elements by id document.getElementById(id) //finds elements by class name document.getElementsByClassName(name) //finds elements by tag name document.getElementsByTagName(name) Example: var arr = document.getElementsByClassName("demo"); Changing the HTML Elements: var element = document.getElementById(“p1”) //using innerHtml element.innerHTML = //new Content //using Attribute element.attribute =//new value //using set attribute element.setAttribute(attr,value) //using Style element.style.property =new style; Adding & Deleting HTML Elements & Events: document.createElements(ele) document.removeChild(ele); document.appendChild(ele) document.replaceChild(ele) Document.getElementById(id).onClick= function(){}; Dom Events onClick Onload Onunload onChange Onmouseover, , Onmouseout, onmousedown, onmouseup onFocus,onblur Creating a new HTML Elements; 1. Create Element 2. Add text to the Element 3. Add as text node to the element and to the existing tree. Example:. var para = document.createElement("p"); var node = document.createTextNode("This is new."); para.appendChild(node); var element = document.getElementById("div1"); element.appendChild(para); // element.insertBefore(para, child); Creating a new HTML Elements; var parent = document.getElementById("div1"); var child = document.getElementById("p1"); parent.removeChild(child); var parent = document.getElementById("div1"); var child = document.getElementById("p1"); parent.replaceChild(para, child); Regular Expression using JavaScript A regular expression is a sequence of characters that forms a search pattern. Syntax: var pattern = new RegExp(pattern, attributes); or var pattern = /pattern/attributes; pattern − A string that specifies the pattern of the regular expression attributes − An optional string containing any of the "g", "i", and "m" Regular Expression using JavaScript [..] = Any one character between the brackets [^..] = Expect those character between the brackets [0-9] = matches any decimal between 0-9 [a-z] = matches lower case alphabets [A-Z] = matches upper case alphabets [a-Z] = matches any character from lower case ‘a’ to upper case ‘Z’. Quantifiers: Used to denote the position. P+ = matches contain any string contain one or more ‘p’ P* = matches contain any string contain zero or more ‘p’ P? = matches contain any string contain at most one ‘p’ P{N} = matches contain any string contain N ‘p’ P{2,3} = matches contain any string contain 2 or 3 ‘p’ P{2,} = matches contain any string contains atleast 2 ‘p’ Regular Expression using JavaScript P$= matches contain any string contain ‘p’ at the end ^p = matches contain any string contain ‘p’ at the beginning. Example: [^a-zA-Z] p.P ^.{2}$ P(hp)* Regular Expression Meta Characters . – Single character \s – whiltespace. \S – non white space \d – [0-9] \D – non digit [\w] – word [\W] – non-word [aeiou] Modifiers: i – case insensitive M – multiline matches G- global. Regular Expression Meta Characters <html> <head> <title>JavaScript RegExp exec Method</title> </head> <body> <script type="text/javascript"> var str = "Javascript is an interesting scripting language"; var re = new RegExp( "script", "g" ); var result = re.exec(str); document.write("Test 1 - returned value : " + result); </script> </body> </html> Regular Expression Meta Characters <html> <head> <title>JavaScript RegExp exec Method</title> </head> <body> <script type="text/javascript"> var str = "Javascript is an interesting scripting language"; var re = new RegExp( "script", "g" ); var result = re.test(str); document.write("Test 1 - returned value : " + result); </script> </body> </html> Thank you ...
View Full Document

  • Fall '19

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

Stuck? We have tutors online 24/7 who can help you get unstuck.
A+ icon
Ask Expert Tutors You can ask You can ask You can ask (will expire )
Answers in as fast as 15 minutes