introduction to java scriptsfor sym.pptx

gayatridwahane 17 views 45 slides Jun 20, 2024
Slide 1
Slide 1 of 45
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45

About This Presentation

regarding java script for symca students


Slide Content

Gokhale Education Society’s R. H. Sapat College of EnginHAeering Management Studies and Research, Nashik Department of MCA Engineering Subject: WEB PROGRAMMING Subject code:410901 Class: SYMCA Prepared by Prof. Gayatri Raut

Javascript Priya goyal

What is JavaScript    JavaScript ("JS" for short) is a full-fledged dynamic programming language that, when applied to an HTML document, can provide dynamic interactivity on websites. It was invented by Brendan Eich, co-founder of the Mozilla project, the Mozilla Foundation, and the Mozilla Corporation. We can do pretty much anything with JavaScript, such as image galleries, fluctuating layouts, and responses to button clicks. And if get more experienced with the language, we'll be able to create games, animated 2D and 3D graphics, full blown database-driven apps, and more!

Advantages of JavaScript   Saving bandwidth and strain on the web server. Javascript is executed on the client side Javascript is relatively fast to the end user Javascript is executed on the client side

Limitations of JavaScript  Security Issues Javascript snippets, once appended onto web pages execute on client servers immediately and therefore can also be used to exploit the user's system. While a certain restriction is set by modern web standards on browsers, malicious code can still be executed complying with the restrictions set.  Javascript rendering varies Different layout engines may render Javascript differently resulting in inconsistency in terms of functionality and interface. While the latest versions of javascript and rendering have been geared towards a universal standard, certain variations still exist.

Client-side JavaScript     A scripting or script language is a programming language that supports scripts , programs written for a special run-time environment that automate the execution of tasks that could alternatively be executed one-by-one by a human operator. Scripting languages are often interpreted (rather than compiled). Client-side scripting generally refers to the class of computer programs on the web that are executed client-side , by the user's web browser, instead of server-side. Client-side scripts do not require additional software on the server (making them popular with authors who lack administrative access to their servers); however, they do require that the user's web browser understands the scripting language in which they are written. Client-side scripting is not inherently unsafe. Users, though, are encouraged to always keep their web browsers up-to-date to avoid exposing their computer and data to new vulnerabilities.

Places to put JavaScript code Between the body tag of html Between the head tag of html In .js file (external javaScript)

Between the body tag  In the above example, we have displayed the dynamic content using JavaScript. Let’s see the simple example of JavaScript that displays alert dialog box. <script type="text/javascript"> alert("Hello Javatpoint"); </script>

Internal Javascript <html> <head> <script> ………JavaScript code……….. </script> </head> <body> </body> < / h t m l> We can place the <script> tags, containing your JavaScript, anywhere within you web page, but it is normally recommended that we should keep it within the <head> tags.

External JavaScript File function sayHello() { alert("Hello World") } <html> <head> <script type="text/javascript" src="filename.js" > ………JavaScript code……….. < / s c r ipt> < / he a d > <bo dy > </body> </html> Test.html Filename.js

Case Sensitivity  JavaScript is a case-sensitive language.

Comments  Single line comment // This is a comment  Multiline comment /* line 1 line 2 line 3 */

Data Types Variable Explanation Example String var myVariable = 'Bob'; Nu m b e r var myVariable = 10; Boolean A string of text. To signify that the variable is a string, you should enclose it in quote marks. A number. Numbers don't have quotes around them. A True/False value. The words true and false are special keywords in JS, and don't need quotes. var myVariable = true; Arr a y A structure that allows you to store multiple values in one single reference. O b j e ct Basically, anything. Everything in JavaScript is an object, and can be stored in a variable. Keep this in mind as you learn. var myVariable = [ 1 , ' B o b ' , 'S t e v e ' , 1 ] ; Refer to each member of the array like this: myVariable[0], myVariable[1], etc. var myVariable = document.querySelector('h1'); All of the above examples too.

Ope r ators          What is an operator? Let us take a simple expression 4 + 5 is equal to 9 . Here 4 and 5 are called operands and ‘+’ is called the operator . JavaScript supports the following types of operators. Assignment operators Comparison operators Arithmetic operators Bitwise operators Bitwise shift operators Logical operators Conditional (ternary) operator

Operator precedence Operator type Individual operators member call / create instance negation/increment multiply/divide addition/subtraction bitwise shift relational equality b i t w i se -a n d bitwise-xor bitwise-or l o g i ca l -a n d logical-or conditional assignment comma . [] () new ! ~ - + ++ -- typeof void delete * / % + - << >> >>> < <= > >= in instanceof == != === !== & ^ | & & || ?: = += -= *= /= %= <<= >>= >>>= &= ^= |= ,

JavaScript Array   JavaScript array is an object that represents a collection of similar type of elements. There are 3 ways to construct array in JavaScript By array literal By creating instance of Array directly (using new keyword) By using an Array constructor (using new keyword)

1) JavaScript array literal    The syntax of creating array using array literal is given below: var arrayname=[value1,value2.....valueN]; As you can see, values are contained inside [ ] and separated by , (comma). Let’s see the simple example of creating and using array in JavaScript. <script> var emp=["Sonoo","Vimal","Ratan"]; for (i=0;i<emp.length;i++){ document.write(emp[i] + "<br/>"); } </script>

2) JavaScript Array directly ( new keyword )   The syntax of creating array directly is given below: var arrayname=new Array(); Here, new keyword is used to create instance of array. Let’s see the example of creating array directly. < s c r i p t > var i; var emp = new Array(); emp[0] = "Arun"; emp[1] = "Varun"; emp[2] = "John"; for (i=0;i<emp.length;i++){ document.write(emp[i] + "<br>"); } </script>

3) JavaScript array constructor (new keyword)   Here, you need to create instance of array by passing arguments in constructor so that we don't have to provide value explicitly. var arrayname=new Array(value1,value2.....valueN); The example of creating object by array constructor is given below. <script> var emp=new Array("Jai","Vijay","Smith"); for (i=0;i<emp.length;i++){ document.write(emp[i] + "<br>"); } </script>

How to access an array   Access the Elements of an Array You refer to an array element by referring to the index number . cars[0] = "Opel"; var cars = ["Saab", "Volvo", "BMW"]; document.getElementById("demo").innerHTML = cars[0]; Access the Full Array With JavaScript, the full array can be accessed by referring to the array name: var cars = ["Saab", "Volvo", "BMW"]; document.getElementById("demo").innerHTML = cars;

Arrays are objects   Arrays are a special type of objects. var person = ["John", "Doe", 46]; Objects use names to access its "members". In this example, person.firstName returns John: var person = {firstName:"John", lastName:"Doe", age:46}; Document.write(person.firstname);

Array Methods   concat() Javascript array concat() method returns a new array comprised of this array joined with two or more arrays. array.concat(value1, value2, ..., valueN); indexOf() Javascript array indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present. array.indexOf(searchElement[, fromIndex]);  LastIndexOf() Javascript array lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex. array.lastIndexOf(searchElement[, fromIndex]);  Join() Javascript array join() method joins all the elements of an array into a string. array.join(separator);  sort() Javascript array sort() method sorts elements of an array. array.sort(function);

Array Methods   Push() Javascript array pop() method insert an element at the end of an array Array.push(value); Pop() Javascript array pop() method removes the last element from an array and returns that element. Array.pop(value);  Reverse() Javascript array reverse() mmethod reverses the element of an array. The first array element becomes the last and the last becomes the first. Array.Reverse();  Unshift() Adds one or more elements to the front of an array and returns the new length of the array. Array.Unshift(value);  Shift() Javascript array shift()method removes the first element from an array and returns that element. Array.Shift();

Array Methods  splice() The splice() method adds/removes items to/from an array, and returns the removed item(s). array.splice(index,howmany,item1,.....,itemX) slice() The slice() method returns the selected elements in an array, as a new array object. array.slice(start,end) index Required. specifies at what position to add/remove items howmany Required. The number of items to be removed item1, ..., itemX Optional. The new item(s) to be added to the array s t a rt Optional. specifies where to start the selection (count starts from index value 0). e n d Optional. specifies where to end the selection. (count starts from 1).

JavaScript String     The JavaScript string is an object that represents a sequence of characters. There are 2 ways to create string in JavaScript By string literal var stringname="string value"; By string object (using new keyword) var stringname=new String("string literal");

JavaScript String Methods     charAt(index) The JavaScript String charAt() method returns the character at the given index. document.write(str.charAt(2)); concat(str) The JavaScript String concat(str) method concatenates or joins two strings. var s1="javascript "; var s2="concat example"; var s3=s1.concat(s2); indexOf(str) The JavaScript String indexOf(str) method returns the index position of the given string. var s1="javascript from javatpoint indexof"; var n=s1.indexOf("from"); lastIndexOf(str) The JavaScript String lastIndexOf(str) method returns the last index position of the given string. var s1="javascript from javatpoint indexof"; var n=s1.lastIndexOf("java");

JavaScript String Methods     toLowerCase() This method returns the given string in lowercase letters. var s1="JavaScript toLowerCase Example"; var s2=s1.toLowerCase(); toUpperCase() This method returns the given string in Uppercase letters. var s1="JavaScript toUpperCase Example"; var s2=s1.toUpperCase(); slice(beginIndex, count) This method returns the parts of string from given beginIndex to count. In slice() method, beginIndex is inclusive and count is exclusive. (beginIndex starts from 0th element of array and count starts from beginIndex) var s2=s1.slice(2,5); trim() This method removes leading and trailing whitespaces from the string. var s1=" javascript trim "; var s2=s1.trim();

Javascript DOM Document Object Model  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 html document. It has properties and methods. By the help of document object, we can add dynamic content to our web page.  window.document Is same as document

Methods Document Object Method Description Example document.write("string") writes the given string on the doucment. document.write(‘’hello”); document.writeln("string") document.write(‘’hello”); document.getElementById() var a=document.getElementById(“p1”).value document.getElementsByName() writes the given string on the doucment with newline character at the end. returns the element having the given id value. returns all the elements having the given name value. var a=document.getElementsByName(“pera”).value document.getElementsByTagName () returns all the elements having the given tag name. var a=document.getElementsByTagName(“p”).value document.getElementsByClassNam e() returns all the elements having the given class name. document.querySelector() Returns the first element that matches a specified CSS selector(s) in the document var a=document.getElementsByClassName(“class1”).val ue Var a = document.querySelector(“.classname”);

Methods Document Object //put ClassName or Name in the place of TagName Example: <body> <p class=“class1” name=“pera” >demo1</p> <p class=“class1” name=“pera” >demo2</p> <p id="p1“ ></p> <script> var x = document.getElementsBy TagName (" p "); document.getElementById("p1").innerHTML =x[0].innerHTML; </script> </body> Output: dem o1 dem o2 dem o3

Methods Document Object Method Description document.title document.URL document.cookie document.createAttribute() document.body document.form() Sets or returns the title of the document Returns the full URL of the HTML document Returns all name/value pairs of cookies in the document Creates an attribute node Sets or returns the document's body (the <body> element) Returns the elements value/name of form <form id="myForm" name="myForm"> <input id="email" name="email" value= "som e @email.com " /> </form> <script> document.forms["myForm"]["email"].value </script>

Adding and Deleting HTML Elements Method Description Create an HTML element Remove an HTML element Add an HTML element Replace an HTML element document.createElement(element) document.removeChild(element) document.appendChild(element) document.replaceChild(element) <body> <div id="d1"> hello </div> <script> var x = document.createElement('span'); x.innerHTML = "Hello!"; //document.body.appendChild(x); //append in body //append in particular element document.getElementById("d1").appendChild(x); </script> </body>

Methods Element Object Method Description Example element.style.property document.getElementById(“p1”).style.color=“red”; element.tagName Sets or returns the value of the style attribute of an element Returns the tag name of an element Var x=document.getElementById(“p1”).tagName element.innerHTML Sets or returns the content of an element p.innerHtml=“hello’; e l e m en t .i d Var x=document.getElementsByTagName(“p”).id element.attribute Sets or returns the value of the id attribute of an element Change the attribute value of an HTML element e l e m en t . s e t A tt r i bu te ( a tt r i bu t e, value) Change the attribute value of an HTML element <img src=“1.jpg”></img> <script> document.getElementById(“img1”).src=“2.jpg” </script> Ex1: document.getElementsByTagName("H1") [0].setAttribute("class", “newclass"); Ex2: element.setAttribute("style", "background-color: red;");

Methods DOM Attribute Object Method Description Example attr.name Returns the name of an attribute a t t r.v a l u e Sets or returns the value of the attribute var a=document.getElementById(“p1”).nam e var a=document.getElementById(“txt1”).valu e innerText Vs innerHTML innerText retrieves and sets the content of the tag as plain text, whereas innerHTML retrieves and sets the same content but in HTML format.

Browser Object model

JavaScript Popup Boxes   It is possible to make three different kinds of popup windows Alert Box   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. alert("sometext"); <script> alert("Hello World!") </script>

JavaScript Popup Boxes - 2  Confirm Box    A confirm 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. confirm("sometext"); <script> function myFunction() { var x; if (confirm("Press a button!") == true) { x = "You pressed OK!"; } else { x = "You pressed Cancel!"; } document.getElementById("demo").innerHTML = x; } </script>

JavaScript Popup Boxes - 3  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. prompt("sometext","defaultText"); Hello Alice! How are you today? <script> function myFunction() { var person = prompt("Please enter your name"); if (person != null) { document.getElementById("demo").innerHTML = "Hello " + person + "! How are you today?"; } } </script>

Timing Events setTimeout() Method setTimeout( function, milliseconds ) Executes a function, after waiting a specified number of milliseconds. setInterval() Method Var id_of_setinterval =setInterval( function, milliseconds ) Same as setTimeout(), but repeats the execution of the function continuously. clearInterval() Method The clearInterval() method stops the executions of the function specified in the setInterval() method. It ret clearInterval( id_of_setinterval ) * There are 1000 milliseconds in one second.

Window History loads the URL in the history list. history.back() - same as clicking back in the browser history.forward() - same as clicking forward in the browser <head> <script> function goBack() { window.history.back() } function goForward() { w i nd o w . h i s to r y .fo r w a rd ( ) } </script> </head> <body> <input type="button" value="Back" onclick="goBack()"> <input type="button" value="Forward" onclick="goForward()"> </body>

Navigator object navigator.appName n a v i g a t o r . appV e r s i o n n a v i g a t o r . appC o de N am e navigator.cookieEnabled navigator.userAgent navigator.language navigator.userLanguage navigator.plugins n a v i g a t o r . s y st e m L a ng ua g e navigator.mimeTypes[] n a v i g a t o r . pl at f o rm navigator.online returns the name returns the version returns the code name returns true if cookie is enabled otherwise false returns the user agent returns the language. It is supported in Netscape and Firefox only. returns the user language. It is supported in IE only. returns the plugins. It is supported in Netscape and Firefox only. returns the system language. It is supported in IE only. returns the array of mime type. It is supported in Netscape and Firefox only. returns the platform e.g. Win32. returns true if browser is online otherwise false. The JavaScript navigator object is used for browser detection. It can be used to get browser information. There are many properties of navigator object that returns information of the browser. Property Description

Window Screen Property Description screen.width returns the width of the visitor's screen screen.height returns the height of the visitor's screen screen.availWidth screen.availHeight screen.colorDepth returns the width of the visitor's screen, in pixels, minus interface features like the Windows Taskbar. returns the height of the visitor's screen, in pixels, minus interface features like the Windows Taskbar. returns the number of bits used to display one color. screen.pixelDepth returns the pixel depth of the screen. It contains information about the user's screen.

HTML/DOM events for JavaScript Events Description onclick on d b l c l i ck onfocus onblur on su b m i t on m o u s e o v e r onmouseout occurs when element is clicked. occurs when element is double-clicked. occurs when an element gets focus such as button, input, textarea etc. occurs when form looses the focus from an element. occurs when form is submitted. occurs when mouse is moved over an element. occurs when mouse is moved out from an element (after moved over). onmousedown occurs when mouse button is pressed over an element. on m o u s e u p occurs when mouse is released from an element (after mouse is pressed). onload onunload onscroll onresized onreset onke yd o w n onkeypress onkeyup occurs when document, object or frameset is loaded. occurs when body or frameset is unloaded. occurs when document is scrolled. occurs when document is resized. occurs when form is reset. occurs when key is being pressed. occurs when user presses the key. occurs when key is released.

References    http://www.javatpoint.com/javascript-tutorial http://www.w3schools.com/js/default.asp https://developer.mozilla.org

T hank y ou
Tags