The time is?"> The time is?">

Presentation is loading. Please wait.

Presentation is loading. Please wait.

LECTURE 7 (ETCS-308) Subject teacher : Ms. Gunjan Beniwal

Similar presentations


Presentation on theme: "LECTURE 7 (ETCS-308) Subject teacher : Ms. Gunjan Beniwal"— Presentation transcript:

1 LECTURE 7 (ETCS-308) Subject teacher : Ms. Gunjan Beniwal
WEB ENGINEERING LECTURE (ETCS-308) Subject teacher : Ms. Gunjan Beniwal

2 JavaScript Events An HTML event can be something the browser does, or something a user does. Here are some examples of HTML events: An HTML web page has finished loading An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected. HTML allows event handler attributes, with JavaScript code, to be added to HTML elements. <some-HTML-element some-event="some JavaScript"> <button onclick='getElementById("demo").innerHTML=Date()'>The time is?</button>

3 Common HTML Events

4 Event Handlers Special-purpose functions that come predefined with JavaScript They are unusual in the sense that they are mostly called from the HTML part of a Web page and not the <SCRIPT> … </SCRIPT> part. Capturing events and responding to them. The system sends events to the program and the program responds to them as they arrive. Events can include things a user does - like clicking the mouse - or things that the system itself does - like updating the clock.

5 Event Driven Programs Programs that can capture and respond to events are called ‘event-driven programs’. JavaScript was specifically designed for writing such programs and almost all programs written in JavaScript are event-driven. Events handlers are placed in the BODY part of a Web page as attributes in HTML tags. Events can be captured and responded to directly with JavaScript one-liners embedded in HTML tags in the BODY portion. Alternatively, events can be captured in the HTML code, and then directed to a JavaScript function for an appropriate response.

6 In-Line JavaScript Event Handling
Event handlers are placed in the BODY portion of a Web page as attributes of HTML tags The event handler attribute consists of 3 parts: The identifier of the event handler The equal sign A string consisting of JavaScript statements enclosed in double or single quotes Multiple JavaScript statements (separated by semicolons) can be placed in that string, but all have to fit in a single line; no newline characters are allowed in that string Due to this limitation, sophisticated event handling is not possible with in-line event handling

7 Example <INPUT type=“submit” name=“send ” value=“Send ” onMouseOver= “if (document.send .sender.value.length < 1) window.alert(‘Empty From field! Please correct’)” > Additional JavaScript code for the smart ‘Send ’ button that does not allow itself to be clicked if the “From” text field is left blank This type of event handling is called ‘in-line JavaScript’ That is, the event was captured and handled with a JavaScript one-liner that was embedded in the HTML tag

8 Example

9 onFocus & onBlur onFocus executes the specified JavaScript code when a window receives focus or when a form element receives input focus onBlur executes the specified JavaScript code when a window loses focus or a form element loses focus

10 onFocus & onBlur JavaScript that goes between the <SCRIPT>, </SCRIPT> tags: function checkAge( ) { if( parseInt( document.form1.age.value ) < 12 ) { window.alert( "Stop! You are younger than 12" ) ; } JavaScript included as an attribute of the INPUT tag: <INPUT type="text" name=“age" onBlur="checkAge( ) ">

11 Complete Example <HTML> <HEAD> <TITLE>onBlur( ) Demo</TITLE> <SCRIPT> function checkAge() { if( parseInt(document.form1.age.value) < 12) { window.alert("Stop! You are younger than 12" ) ; } } </SCRIPT> </HEAD> <BODY bgcolor="#66FFCC"> <FORM name="form1" method="post" action=""> <TABLE border="1"> <TR> <TD>Age</TD> <TD><INPUT type="text" name="age" onBlur="checkAge()"> </TD></TR><TR> <TD>Phone Number</TD> <TD><INPUT type="text" name="phNo"></TD> </TR><TR> <TD><INPUT type="reset" value="Reset"></TD> <TD><INPUT type="submit" value="Submit"></TD></TR> </TABLE></FORM></BODY> </HTML>

12 onLoad & onUnload onLoad executes the specified JavaScript code when a new document is loaded into a window. onUnload executes the specified JavaScript code when a user exits a document.

13 Example: onUnload <HTML> <HEAD> <TITLE>onUnload Demo</TITLE> <SCRIPT> function annoyUser( ) { currentUrl = window.location ; window.alert( "You can't leave this page" ) ; window.location = currentUrl ; } </SCRIPT></HEAD> <BODY onUnload="annoyUser( )"> This page uses the onUnload event handler … </BODY></HTML>

14 Example: onUnload

15 More Uses for onLoad/onUnload
onLoad can be used to open multiple Windows when a particular document is opened onUnload can be used to say “Thank you for the visit” when a user is leaving a Web page At times, a user opens multiple inter- dependent windows of a Web site. onUnload can be used to warn that all child Windows will become inoperable if the user closes the parent Window

16 Important Points Mixed-case capitalization of event handlers (e.g. onClick) is a convention (but not a requirement) for JavaScript event handlers defined in HTML code. Using ‘ONCLICK’ or ‘onclick’ as part of a an HTML tag is perfectly legal as well. At times, you may wish to use event handlers in JavaScript code enclosed in <SCRIPT>, </SCRIPT> tags. In those cases you have to strictly follow the JavaScript rule for all event handler identifiers: they must all be typed in small case, e.g. ‘onclick’ or ‘onmouseover’.

17 A misleading statement
JavaScript is case sensitive. Only the first of the following will result in the desired function – the rest will generate errors or other undesirable events: onMouseClick – OnMouseClick onmouseclick – ONMOUSECLICK That statement is incorrect in two ways: All four will work fine as part of HTML tags Only the ‘all small case’ version will be interpreted as intended in JavaScript code

18 Submit and reset events
submit and reset events fire when a form is submitted or reset, respectively The anonymous function executes in response to the user’s submitting the form by clicking the Submit button or pressing the Enter key. confirm method asks the users a question, presenting them with an OK button and a Cancel button. If the user clicks OK, confirm returns true; otherwise, confirm returns false. By returning either true or false, event handlers dictate whether the default action for the event is taken. If an event handler returns true or does not return a value, the default action is taken once the event handler finishes executing.

19 Event Bubbling The process whereby events fired on child elements “bubble” up to their parent elements. When an event is fired on an element, it is first delivered to the element’s event handler (if any), then to the parent element’s event handler (if any) If you intend to handle an event in a child element alone, you should cancel the bubbling of the event in the child element’s event-handling code by using the cancelBubble property of the event object.

20 Event Bubbling The bubbles event property returns a Boolean value that indicates whether or not an event is a bubbling event. Event bubbling directs an event to its intended target, it works like this: A button is clicked and the event is directed to the button If an event handler is set for that object, the event is triggered If no event handler is set for that object, the event bubbles up (like a bubble in water) to the objects parent The event bubbles up from parent to parent until it is handled, or until it reaches the document object.

21 Example <!DOCTYPE html> Property <html> <body>
<p>Click the button to find out if the onclick event is a bubbling event.</p> <button onclick="myFunction(event)">Try it</button> <p id="demo"></p> <script> function myFunction(event) { var x = event.bubbles; document.getElementById("demo").innerHTML = x; } </script> </body> </html> Property var x = event.bubbles; If it returns ‘true’ then The event can bubble.

22 JavaScript Strings A JavaScript string simply stores a series of characters like "John Doe". A string can be any text inside quotes. You can use single or double quotes: var carname = "Volvo XC60"; var carname = 'Volvo XC60'; You can use quotes inside a string, as long as they don't match the quotes surrounding the string: var answer = "It's alright"; var answer = "He is called 'Johnny'"; var answer = 'He is called "Johnny"';

23 JavaScript Strings This is the list of special characters that can be added to a text string with the backslash sign: Code Outputs \' single quote \" double quote \\ backslash \n new line \r carriage return \t tab \b backspace \f form feed

24 JavaScript Strings String Properties and Methods Primitive values, like "John Dave", cannot have properties or methods (because they are not objects). But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties. String Properties Property Description constructor Returns the function that created the String object's prototype length Returns the length of a string prototype Allows you to add properties and methods to an object

25 String Methods Method Description charAt()
Returns the character at the specified index (position) charCodeAt() Returns the Unicode of the character at the specified index concat() Joins two or more strings, and returns a copy of the joined strings fromCharCode() Converts Unicode values to characters indexOf() Returns the position of the first found occurrence of a specified value in a string lastIndexOf() Returns the position of the last found occurrence of a specified value in a string localeCompare() Compares two strings in the current locale match() Searches a string for a match against a regular expression, and returns the matches replace() Searches a string for a value and returns a new string with the value replaced

26 String Methods Method Description search()
Searches a string for a value and returns the position of the match slice() Extracts a part of a string and returns a new string split() Splits a string into an array of substrings substr() Extracts a part of a string from a start position through a number of characters substring() Extracts a part of a string between two specified positions toLocaleLowerCase() Converts a string to lowercase letters, according to the host's locale toLocaleUpperCase() Converts a string to uppercase letters, according to the host's locale toLowerCase() Converts a string to lowercase letters toString() Returns the value of a String object toUpperCase() Converts a string to uppercase letters trim() Removes whitespace from both ends of a string valueOf() Returns the primitive value of a String object

27 String Methods <!DOCTYPE html> <html> <body>
<p>The charCodeAt() method returns the unicode of the character at a given position in a string:</p> <p id="demo"></p> <script> var str = "HELLO WORLD"; document.getElementById("demo").innerHTML = str.charCodeAt(0); </script> </body> </html> var str = "Please locate where 'locate' occurs!"; var pos = str.indexOf("locate"); var pos = str.lastIndexOf("locate"); var pos = str.search("locate"); var str = "Apple, Banana, Kiwi"; var res = str.slice(7,13); var res = str.substring(7,13); var str = "Please visit Microsoft!"; var n = str.replace("Microsoft","W3Schools"); var text2 = str.toUpperCase()

28 Number Properties and Methods
Primitive values (like 3.14 or 2014), cannot have properties and methods (because they are not objects). But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties. Number Properties Property Description MAX_VALUE Returns the largest number possible in JavaScript MIN_VALUE Returns the smallest number possible in JavaScript NEGATIVE_INFINITY Represents negative infinity (returned on overflow) NaN Represents a "Not-a-Number" value POSITIVE_INFINITY Represents infinity (returned on overflow)

29 Number Properties and Methods
Global Methods JavaScript global functions can be used on all JavaScript data types. These are the most relevant methods, when working with numbers: Method Description Number() Returns a number, converted from its argument. parseFloat() Parses its argument and returns a floating point number parseInt() Parses its argument and returns an integer

30 Number Properties and Methods
Number Methods Method Description toString() Returns a number as a string toExponential() Returns a string, with a number rounded and written using exponential notation. toFixed() Returns a string, with a number rounded and written with a specified number of decimals. toPrecision() Returns a string, with a number written with a specified length valueOf() Returns a number as a number

31 JavaScript Math Object
The Math object allows you to perform mathematical tasks. The Math object includes several mathematical methods. Math Object Methods Method Description abs(x) Returns the absolute value of x acos(x) Returns the arccosine of x, in radians asin(x) Returns the arcsine of x, in radians atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians atan2(y,x) Returns the arctangent of the quotient of its arguments ceil(x) Returns x, rounded upwards to the nearest integer

32 Math Object

33 Math Object Methods

34 Contd..

35 JavaScript Form Validation
HTML form validation can be done by a JavaScript. If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the form from being submitted:

36 Data Validation Data validation is the process of ensuring that computer input is clean, correct, and useful. Typical validation tasks are: has the user filled in all required fields? has the user entered a valid date? has the user entered text in a numeric field? Most often, the purpose of data validation is to ensure correct input to a computer application.

37 Contd.. Validation can be defined by many different methods, and deployed in many different ways. Server side validation is performed by a web server, after input has been sent to the server. Client side validation is performed by a web browser, before input is sent to a web server

38 Constraint Validation DOM Methods

39 Constraint Validation DOM Properties

40 Example <!DOCTYPE html> <html> <body> <p>Enter a number and click OK:</p> <input id="id1" type="number" min="100" max="300"> <button onclick="myFunction()">OK</button> <p>If the number is less than 100 or greater than 300, an error message will be displayed.</p> <p id="demo"></p>

41 <script> function myFunction() { var inpObj = document.getElementById("id1"); if (inpObj.checkValidity() == false) { document.getElementById("demo").innerHTML = inpObj.validationMessage; } else { document.getElementById("demo").innerHTML = "Input OK"; } </script> </body> </html>

42 Output

43 Thank You!!


Download ppt "LECTURE 7 (ETCS-308) Subject teacher : Ms. Gunjan Beniwal"

Similar presentations


Ads by Google