Javascript Functions Content * Functions * Syntax * Return Statement * Events * List of Event Attributes * Form Validation Functions * A function contains code that will be executed by an event or by a call to the function. * You may call a function from anywhere within a page (or even from other pages if the function is embedded in an external .js file). * Functions can be defined both in the <head> and in the <body> section of a document. Syntax function functionname(var1,var2,...,var n) { some code; } * The word function must be written in lowercase letters. * If you declare a variable, using "var", within a function, the variable can only be accessed within that function. * When you exit the function, the variable is destroyed. These variables are called local variables. Example <script type="text/javascript"> function area(length,breadth) { var a=length*breadth; document.write(“Area of Rectangle is “+a); } </script> Return statement * The return statement is used to specify the value that is returned from the function. Example <script type="text/javascript"> function area(length,breadth) { var a=length*breadth; return(a); } </script> Events * HTML events are "things" that happen to HTML elements. * When JavaScript is used in HTML pages, JavaScript can "react" on these events * An HTML event can be something the browser does, or something a user does * JavaScript lets you execute code when events are detected * HTML allows event handler attributes, with JavaScript code, to be added to HTML elements * Examples of events * When a user clicks the mouse * When a web page has loaded * When an image has been loaded * When the mouse moves over an element * When an input field is changed * When an HTML form is submitted * When a user strokes a key * <'some-HTML-element' some-event='some JavaScript'> Example <html> <body> <button onclick="getElementById('sample').innerHTML=Date()">Date and Time</button> <p id="sample"></p> </body> </html> * In the above example, an onclick event attribute is added to a button element. As soon as user clicks the button, date and time will appear. Date() is a built-in function. * Another way is to put everything in a javascript function can invoke on a button click. Example <html> <body> <p>Click the button to display the date.</p> <button onclick="displayDate()">Date and Time</button> <script> function displayDate() { document.getElementById("sample").innerHTML = Date(); } </script> <p id="sample"></p> </body> </html> List of Event Attributes * There are several event attributes we can use with HTML tags and bind them with some javascript code. * Here is the list of event attributes Event Name - Description * onclick - The event occurs when the user clicks on an element * ondblclick - The event occurs when the user double-clicks on an element * onmousedown - The event occurs when a user presses a mouse button over an element * onmouseover - The event occurs when the pointer is moved onto an element * onmousemove - The event occurs when the pointer is moving while it is over an element * onmouseout - The event occurs when a user moves the mouse pointer out of an element * onmouseup - The event occurs when a user releases a mouse button over an element * onkeydown - The event occurs when the user is pressing a key * onkeypress - The event occurs when the user presses a key * onkeyup - The event occurs when the user releases a key * onload - The event occurs when a document, frameset, or <object> has been loaded * onresize - The event occurs when a document view is resized * onscroll - The event occurs when a document view is scrolled * onunload - The event occurs once a page has unloaded (for <body> and <frameset>) * onblur - The event occurs when a form element loses focus * onchange - The event occurs when the content of a form element, the selection, or the checked state have changed (for <input>, <select>, and <textarea>) * onfocus - The event occurs when an element gets focus (for <label>, <input>, <select>, textarea>, and <button>) * onselect - The event occurs when a user selects some text (for <input> and <textarea>) * onsubmit - The event occurs when a form is submitted Example: Display Mouse position <html> <head> <title>mouse Example</title> <style type="text/css"> </style> <script type="text/javascript"> function f1(event) { var ptag=document.getElementsByTagName("p"); ptag[0].innerHTML="x="+event.clientX+" y="+event.clientY; } </script> </head> <body onmousemove="f1(event)"> <h1> Move mouse to see mouse coordinates </h1> <p></p> </body> </html> Example: Change background when mouse move over a paragraph <html> <head> <script type="text/javascript"> function effect1(para) { para.style.backgroundColor="pink"; } function effect2(para) { para.style.backgroundColor="white"; } </script> </head> <body> <h2>Move mouse on paragraph and see changes</h2> <p onmouseover="effect1(this)" onmouseout="effect2(this)"> ITRun is a premier organization founded in 1990, growing as an IT Training/service providers and determined to set high standards in IT industry. Initially started as an IT training institute, we have now expanded to include software development as well as IT Consultant Services. Currently we operate as three strategic business units focusing on – IT Training, IT Development, and IT Solutions. There are several activities which we are carrying out simultaneously to achieve this goal. We are offering courses in hottest and most demanded technologies of this area like C, C++ C#(sharp), Oracle, VC++, Java, Advance Java, VB.Net, ASP.Net, PHP, Android, Networking and IPv6 Area (CCNA, CNE6 – Level 1(Silver) and CNE6 – Level 2 (Gold)) also. We also encourage students to learn and adopt standards of software development process. From its establishment onwards ITRun has created a niche for itself in the education and software sector. We are working for the promotion of latest technologies in IT along with providing a solid basic foundation to a student to stand firmly in this competitive and cut through era. </p> </body> </html> Example: Add two numbers on a click of button <html> <head> <title> JAVASCRIPT </title> <script type="text/javascript" > function add() { var x=parseInt(document.getElementById("i1").value); var y=parseInt(document.getElementById("i2").value); var z=x+y; document.write("Sum is "+z); } </script> </head> <body> First Number:<input id="i1" type="text" /><br/> Second Number:<input id="i2" type="text" /><br/> <button onclick="add()">Add</button> </body> </html> Form Validation * JavaScript can be used to validate data in HTML forms before sending off the content to a server * Javascript can check - the user left required fields empty - the user entered a valid e-mail address - the user entered a valid date - the user entered text in a numeric field * Create a javascript function and get input element. * Use decision control and compare input value with empty string ("") or null. * Use isNaN() method of javascript to check if data is not a number. Example: Checking an email function validateForm() { var x=document.forms["myForm"]["email"].value; var atpos=x.indexOf("@"); var dotpos=x.lastIndexOf("."); if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) { alert("Not a valid e-mail address"); return false; } } Example: A Complete example of form validation form.html <html> <head> <title>Form Validation </title> <link rel="stylesheet" href="formstyle.css"/> <script type="text/javascript" > function focus1() { document.getElementsByName("name")[0].focus(); } function validation() { var err=0; var n1=document.getElementsByName("name"); var n2=document.getElementsByName("mobile"); var n3=document.getElementsByName("gender"); var n4=document.getElementsByName("pwd"); if(n1[0].value.length==0) { document.getElementById("s1").innerHTML="*"; document.getElementById("s1").style.color="red"; err=1; } else document.getElementById("s1").innerHTML=""; if(n2[0].value.length!=10) { document.getElementById("s2").innerHTML="*"; document.getElementById("s2").style.color="red"; err=1; } else document.getElementById("s2").innerHTML=""; if(n3[0].checked==false && n3[1].checked==false) { document.getElementById("s3").innerHTML="*"; document.getElementById("s3").style.color="red"; err=1; } else document.getElementById("s3").innerHTML=""; if(n4[0].value.length<4) { document.getElementById("s4").innerHTML="*"; document.getElementById("s4").style.color="red"; err=1; } else document.getElementById("s4").innerHTML=""; var n5=document.getElementsByName("c"); var n6=document.getElementsByName("cpp"); var n7=document.getElementsByName("php"); if(n5[0].checked==false&&n6[0].checked==false&&n7[0].checked==false) { document.getElementById("s5").innerHTML="*"; document.getElementById("s5").style.color="red"; err=1; } else document.getElementById("s5").innerHTML=""; if(err==1) return(false); return(true); } </script> </head> <body onload="focus1()"> <form action="validate.php" method="get" > <table> <caption>Registration Form </caption> <tr> <td>Name</td> <td><input type="text" name="name"/><span id="s1"></span></td> </tr> <tr> <td>Mobile</td> <td><input type="text" name="mobile"/><span id="s2"></span></td> </tr> <tr> <td>Gender</td> <td> <input type="radio" name="gender" value="male"/>Male<span id="s3"></span><br/> <input type="radio" name="gender" value="female"/>Female </td> </tr> <tr> <td>Password</td> <td><input type="password" name="pwd"/><span id="s4"></span></td> </tr> <tr> <td>Courses</td> <td><input type="checkbox" name="c"/>C<span id="s5"></span><br/> <input type="checkbox" name="cpp"/>C++<br/> <input type="checkbox" name="php"/>PHP<br/> </td> </tr> <tr> <td>City</td> <td> <select name="city"> <option> Bhopal</option> <option> Indore</option> <option> Jabalpur</option> <option> Indore</option> </select> </td> </tr> <tr> <td></td> <td><input id="submit" type="submit" value="submit" name="submit" onclick="return validation()"/></td> </tr> </table> </form> </body> </html> formstyle.css body { background-color:lightblue; } table { position:fixed; left:300px; border:2px solid black; } table caption { font-size:30px; color:navy; } table tr { background-color:lightgreen; height:40px; } table tr td { padding:5px; font-weight:bold; color:brown; } form { position:fixed; left:265px; border:2px solid red; height:400px; width:300px; } #submit { background-color:green; color:yellow; font-weight:bold; } <<Prev Home Next>>
Showing posts with label Javascript Statements. Show all posts
Showing posts with label Javascript Statements. Show all posts
Tuesday, July 4, 2017
Javascript Functions
Monday, July 3, 2017
Control Statement and DOM
Control Statement and DOM Content * Decision Control * Loop * DOM Decision Control * If you are familiar with C language or any other programming language, you must be aware of decision control. any programming language must have decision capability. This can be implemented in Javascript with the following ways * if * if else * Conditional Operator (? :) * Switch Case control * Syntax is exactly same as you have studied in C language. for the completeness of the content we will cover the syntax and example of all possible ways to implement decision control. Syntax of if if(condition) { //code here } Example <script type="text/javascript"> var x=prompt("Enter your age"); if(x<18) document.write("You are minor"); if(x>=18) document.write("You can cast your vote"); </script> Syntax of if else if(condition){ //code here } else { //code here } Example <script type="text/javascript"> var x=prompt("Enter your age"); if(x<18) document.write("You are minor"); else document.write("You can cast your vote"); </script> Syntax of Conditional operator expression1 ? expression2 : expression3; Example <script type="text/javascript"> var x=prompt("Enter your age"); x<18 ? document.write("You are minor") :document.write("You can cast your vote"); </script> Syntax of switch case Control switch(expression) { case constant1: //code here break; case constant2: //code here break; case constant3: //code here break; ... default: //code here } * Use the switch statement to select one of many blocks of code to be executed * The switch expression is evaluated once * If there is a match, the associated block of code is executed. * The value of the expression is compared with the values of each case. * When the JavaScript code interpreter reaches a break keyword, it breaks out of the switch block * The default keyword specifies the code to run if there is no case match Example <script type="text/javascript"> var text; switch (new Date().getDay()) { case 6: text = "Today is Saturday"; break; case 0: text = "Today is Sunday"; break; default: text = "Looking forward to the Weekend"; } document.write(text); </script> Loop * Loops are iterative control statements, used to repeat set of code till some criteria matches. * In javascript we have four ways to implement loops: * for * for/in * while * do/while Syntax of for loop for(statement1;statement2;statement3) { //code here } Statement 1 is executed before the loop (the code block) starts. It is normally initialization of counter variable. Statement 2 defines the condition for running the loop Statement 3 is executed each time after the loop (the code block) has been executed. It is normally updating counter variable. Example <script type="text/javascript"> var text = ""; for (var i = 0; i < 5; i++) { text += "The number is " + i + "<br>"; document.write(text); } </script> Syntax of for/in loop for(var x in array) { //code here } * x is any variable * array is any array variable containing n elements * loop execute code block n number of times. * This loop is used to access array elements in a sequential manner. Example <script type="text/javascript"> var list={0:10, 1:20, 2:30 ,3:40, 4:50}; for (var x in list) { document.write(list[x]+"<br/>"); } </script> Syntax of while loop while(condition) { //code here } Example <script type="text/javascript"> var i=1; while (i<=10) { document.write("5 x "+i+" = "+i*5+"<br/>"); i++; } </script> Syntax of do/while loop do { //code here } while(condition); Example <script type="text/javascript"> var i=1; do{ document.write("5 x "+i+" = "+i*5+"<br/>"); i++; } while (i<=10); </script> DOM * With the HTML DOM, JavaScript can access and change all the elements of an HTML document. * Dom is Document Object ModelDOM Methods * There are several Dom methods that we can use to do variety of job, but we are going to cover the most common methods. * getElementById() * getElementsByTagName() * getElementByClassName() * As the name describes getElementById() finds an element by element id * Similarly getElementsByTagName() finds an array of elements by element Tag Name. * Also the getElementsByClassName() finds an array of elements by element class * getElementById() returns an object that represent HTML element, you can use various properties of this object to manipulate and access HTML element. * one of the property is innerHTML. You can access or change the HTML element content using this property. * You can also alter or set CSS properties of HTML elements through style property. * Following example gives you the glimpse of use of these properties and functions. Example <html> <head> <title>Document Methods</title> </head> <body> <h1 id="head1">Document Method Example</h1> <p id="p1">This is a paragraph</p> <script type="text/javascript"> var x=document.getElementsByTagName("p"); alert("As soon as you click ok, u will see change in paragraph"); x[0].innerHTML="This is changed now"; x[0].style.border="2px solid gray"; var y=document.getElementById("head1"); y.style.color="red"; y.style.textDecoration="underline"; </script> </body> </html> <<Prev Home Next>>
Saturday, July 1, 2017
Java Script
JavaScript Content * Introduction to Javascript * Where to write script block * Javascript Statements * Javascript Comments * Variables * Data Types * Arrays * Alert box * Confirm box * Prompt box Introduction to Javascript * JavaScript is used in web pages to add functionality, validate forms, communicating with server and read write html elements. * JavaScript is a client side scripting language. * JavaScript is an interpreted language, rather than compiled language. * As the browser goes through the JavaScript, it passes it to a special program called interpreter, which converts the JavaScript to the machine code your computer understands * Browsers come equipped with JavaScript interpreters. * Initially it was known as LiveScript * It was first available with Netscape Navigator 2. * Netscape decided to change its name to JavaScript as Java was the hot technology of the time. * Following is the script tag for javascript <script type="text/javascript"> ... ... </script> Where to write Script Block * Either between <head> and </head> or between <body> and </body> * If we want to run the <script> before page loads then it is kept in the <head> section. * If we want to run the <script> after the page loads so that it can interact with HTML elements then it is kept in the <body> section. * JavaScript can also be placed in external files. * External script cannot contain the <script></script> tags * <script type="text/javascript" src="myscript.js"> </script> JS Statements * JavaScript is a sequence of statements to be executed by the browser. * JavaScript is case sensitive language. * Example <script type="text/javascript"> document.write("JavaScript Example"); </script> * document is an object * write is a function or method used to print message on web page * It is normal to add a semicolon at the end of each executable statement * However, semicolon is optional according to the JavaScript standards JS Comments * Comments can be added to explain the JavaScript, or to make the code more readable. * Single line comments start with //. * Multi line comments start with /* and end with */. Variables * JavaScript variables are used to hold values or expressions. * Variable names are case sensitive. * Variable names must begin with a letter or the underscore character * A variables value can change during the execution of a script * Declaring JavaScript variable with var keyword * var x; The above declaration creates a variable name x and contains nothing. However we can initialize variable during declaration. * var x=2; If you redeclare a JavaScript variable, it will not lose its value. * When you assign a text value to a variable, use quotes around the value. * var y="saurabh"; If you assign values to variables that have not yet been declared, the variables will automatically be declared as global variables * N="Saurabh"; Important note * Every non zero value is true, 0 is false * You can compare two strings unlike C language Example <script type="text/javascript"> var s1="amit"; var s2="amar"; if(s1==s2) document.write("Strings are same"); else document.write("Strings are not same"); </script> Data Type * Javascript has dynamic types, this means that the same variable can be used as different types * You can assign boolean values * var x=true; * var x=false; Displaying Variable value To display a variables value we just have to pass it’s name to the document.write( ) method. var a=10; document.write(a); To print a variable’s value with some text we use operator " + " var a=10; document.write(‘Value of a is ‘+a); Arrays * var students= new Array(); students[0]="Amit"; students[1]="Mita"; students[2]="bunty"; * var students= new Array("Amit","Mita","bunty"); * var students= ["Amit","Mita","bunty"]; * You can always use length property of array * For example in the above case students.length is 3. Alert Box * An alert box is often used if you want to make sure information comes through the user * When an alert box pops up, the user will have to click "OK" to proceed. * alert("some text"); Example <script type="text/javascript"> alert("Welcome to home page"); </script> 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 * variable=confirm("some text"); * Variable would get either true or false as a value. Example <script type="text/javascript"> var x = confirm("Are you interested in learning?"); if(x) document.write("Good, you are a geek"); else document.write("Ok, clap for others!!!"); </script> 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 * var x=prompt("some text", "default value"); Example <html> <head> <title> JAVASCRIPT </title> <script type="text/javascript" > var x=parseInt(prompt("Enter a number","0")); var i=1; while(i<=10) { a=i*x; document.write(x+" x "+i+" = "+a+"<br/>"); ++i; } </script> </head> <body> </body> </html> <<Prev Home Next>>
Subscribe to:
Posts (Atom)