Java script ppt from students in internet technology
SherinRappai
42 views
78 slides
Apr 30, 2024
Slide 1 of 78
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
About This Presentation
Java script ppt from students in internet technology
Size: 3.63 MB
Language: en
Added: Apr 30, 2024
Slides: 78 pages
Slide Content
Internet Technology Unit – IV Javasript
A client-side script is a program that may accompany an HTML document or be embedded directly in it. The program executes on the client's machine when the document loads, or at some other time such as when a link is activated. HTML's support for scripts is independent of the scripting language. INTRODUCTION TO SCRIPTS
JavaScript was designed to 'plug a gap' in the techniques available for creating web-pages. HTML is relatively easy to learn, but it is static . It allows the use of links to load new pages, images, sounds, etc., but it provides very little support for any other type of interactivity. Java Script - History
To create dynamic material it was necessary to use either: CGI (Common Gateway Interface) programs · Can be used to provide a wide range of interactive features
The Browser Object Model (BOM) in JavaScript includes the properties and methods for JavaScript to interact with the web browser. BOM provides you with a window objects, for example, to show the width and height of the window. It also includes the window. Screen object to show the width and height of the screen. Browser and Document object
The browser object represents the web browser itself and provides methods and properties for interacting with the browser environment. It typically includes objects and functionalities related to the browser window, history, location, and navigation. Some common browser objects include: window : The global object representing the browser window. It provides access to various properties and methods related to the browser environment. document : The object representing the current web page loaded in the browser window. navigator : The object containing information about the browser, such as its name, version, and platform. location : The object representing the URL of the current web page and providing methods for manipulating the browser's location. These browser objects can be accessed and manipulated using JavaScript, allowing developers to control various aspects of the browsing experience. Browser object
DOM is a fundamental concept in web development, providing a structured and programmable way to interact with HTML documents, enabling the creation of dynamic and interactive web pages. It serves as the entry point for accessing and manipulating the elements, attributes, and text content of the web page. Some common properties and methods of the document object include: getElementById() : A method for retrieving an element from the DOM using its unique identifier (ID). getElementsByClassName () : A method for retrieving elements from the DOM using their class names. getElementsByTagName () : A method for retrieving elements from the DOM using their tag names. createElement () : A method for creating a new HTML element dynamically. document.createElement ( tagName ); appendChild (): A method for adding a new child element to an existing element in the DOM. This method is typically called on a parent element to which you want to append a child element parentElement.appendChild ( childElement ); Document object
1. <!DOCTYPE html> <html> <head> <title>Example</title> </head> <body> < div id=" myDiv ">This is a div element with an id of " myDiv ".</div> <script> // Using getElementById to select the element with id " myDiv " var element = document. getElementById (" myDiv "); // Manipulating the selected element element.style.color = "red"; // Changing text color to red </script> </body> </html> 2. <!DOCTYPE html> <html> <head> <title>Example</title> <style> .highlight { background- color : yellow; } </style> </head> <body> <p class="highlight">This paragraph has the "highlight" class.</p> <p>This paragraph does not have any class.</p> <script> var elements = document. getElementsByClassName ("highlight"); // Manipulating the selected elements for (var i = 0; i < elements.length ; i ++) {elements[ i ]. style.fontWeight = "bold"; // Making text bold } </script> </body> </html> 3. // Using getElementsByTagName to select all <p> elements var document . getElementsByTagName ( "p" );
We can add JavaScript code in an HTML document by employing the dedicated HTML tag <script> that wraps around JavaScript code. The <script> tag can be placed in the <head> section of your HTML, in the <body> section, or after the </body> close tag, depending on when you want the JavaScript to load Scripts and HTML Document
The <script> Tag In HTML, JavaScript code is inserted between <script> and </script> tags.
Comments can be put into any place of a script. They don’t affect its execution because the engine simply ignores them. One-line comments start with two forward slash characters // Ex // This comment occupies a line of its own Multiline comments start with a forward slash and an asterisk /* and end with an asterisk and a forward slash */. Ex /* An example with two messages. This is a multiline comment.*/ Comments
Using var (2015) Using let (after 2015) Using const Using nothing 4 Ways to Declare a JavaScript Variable:
A variable is a “named storage” for data. We can use variables to store goodies, visitors, and other data. To create a variable in JavaScript, use the let keyword. The statement below creates (in other words: declares ) a variable with the name “message”: let message; We can put some data into it by using the assignment operator =: let message; message = 'Hello'; // store the string Variables
Datatypes
Datatypes
An expression is a combination of values, variables, and operators , which computes to a value 5*10 X+40 "John" + " " + "Doe" Expression
Arithmetic Operators Assignment Operators Comparison Operators Logical Operators Conditional Operators Type Operators Types of JavaScript Operators
Operator Description + Addition - Subtraction * Multiplication ** Exponentiation / Division % Modulus (Division Remainder) ++ Increment -- Decrement Arithmetic Operators are used to perform arithmetic on numbers
Arithmetic Operators Operators in JavaScript Sr.No Operator & Description 1 + (Addition) Adds two operands Ex: A + B will give 30 2 - (Subtraction) Subtracts the second operand from the first Ex: A - B will give -10 3 * (Multiplication) Multiply both operands Ex: A * B will give 200 4 / (Division) Divide the numerator by the denominator Ex: B / A will give 2
5 % (Modulus) Outputs the remainder of an integer division Ex: B % A will give 0 6 ++ (Increment) Increases an integer value by one Ex: A++ will give 11 7 -- (Decrement) Decreases an integer value by one Ex: A-- will give 9
Assignment operators assign values to JavaScript variables. The Addition Assignment Operator (+=) adds a value to a variable. let x = 5 + 5; let y = "5" + 5; let z = "Hello" + 5; 10 55 Hello5 Assignment operators
Operator Example Same As = x = y x = y += x += y x = x + y -= x -= y x = x - y *= x *= y x = x * y /= x /= y x = x / y %= x %= y x = x % y **= x **= y x = x ** y
Operator Description == equal to === equal value and equal type != not equal !== not equal value or not equal type > greater than < less than >= greater than or equal to <= less than or equal to ? ternary operator Comparison
Sr.No . Operator & Description 1 = = (Equal) Checks if the value of two operands are equal or not, if yes, then the condition becomes true. Ex: (A == B) is not true. 2 != (Not Equal) Checks if the value of two operands are equal or not, if the values are not equal, then the condition becomes true. Ex: (A != B) is true. 3 > (Greater than) Checks if the value of the left operand is greater than the value of the right operand, if yes, then the condition becomes true. Ex: (A > B) is not true. 4 < (Less than) Checks if the value of the left operand is less than the value of the right operand, if yes, then the condition becomes true. Ex: (A < B) is true. 5 >= (Greater than or Equal to) Checks if the value of the left operand is greater than or equal to the value of the right operand, if yes, then the condition becomes true. Ex: (A >= B) is not true. 6 <= (Less than or Equal to) Checks if the value of the left operand is less than or equal to the value of the right operand, if yes, then the condition becomes true. Ex: (A <= B) is true. Comparison Operators
Sr.N0 Operator & Description 1 && (Logical AND) If both the operands are non-zero, then the condition becomes true. Ex: (A && B) is true. 2 || (Logical OR) If any of the two operands are non-zero, then the condition becomes true. Ex: (A || B) is true. 3 ! (Logical NOT) Reverses the logical state of its operand. If a condition is true, then the Logical NOT operator will make it false. Ex: ! (A && B) is false. Logical Operators
html> <body> <h2>The += Operator</h2> <p id="demo"></p> <script> var x = 10; x += 5; document.getElementById ("demo"). innerHTML = x; </script> </body> </html> Assignment Operator
TYPE OPERATOR
Converting Strings to Numbers Converting Numbers to Strings Converting Dates to Numbers Converting Numbers to Dates Converting Booleans to Numbers Converting Numbers to Booleans Type Conversion
The global method Number() converts a variable (or a value) into a number. Converting Strings to Numbers
The global method String() can convert numbers to strings. It can be used on any type of numbers, literals, variables, or expressions: Converting Numbers to Strings
Converting Dates to Numbers
Converting Dates to Strings
Method Description getFullYear() Get year as a four digit number (yyyy) getMonth() Get month as a number (0-11) getDate() Get day as a number (1-31) getDay() Get weekday as a number (0-6) getHours() Get hour (0-23) getMinutes() Get minute (0-59) getSeconds() Get second (0-59) getMilliseconds() Get millisecond (0-999) getTime() Get time (milliseconds since January 1, 1970) Date Methods
The if Statement Use the if statement to specify a block of JavaScript code to be executed if a condition is true. Syntax if (condition) { // block of code to be executed if the condition is true } Conditional Statements
if ( condition ) { // block of code to be executed if the condition is true } else { // block of code to be executed if the condition is false } else
if ( condition1 ) { // block of code to be executed if condition1 is true } else if ( condition2 ) { // block of code to be executed if the condition1 is false and condition2 is true } else { // block of code to be executed if the condition1 is false and condition2 is false } else -if
Syntax switch( expression ) { case x : // code block break; case y : // code block break; default: // code block } The JavaScript Switch Statement
The while Loop The most basic loop in JavaScript is the while loop which would be discussed in this chapter. The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true. Once the expression becomes false, the loop terminates. Loop in JavaScript
Syntax The syntax of while loop in JavaScript is as follows − while (expression) { Statement(s) to be executed if expression is true }
The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. Syntax The syntax for do-while loop in JavaScript is as follows − Do { Statement(s) to be executed;} while (expression); The do...while Loop
The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins. The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop. The iteration statement where you can increase or decrease your counter. For Loop
Syntax The syntax of for loop is JavaScript is as follows − for (initialization; test condition; iteration statement) { Statement(s) to be executed if test condition is true }
Before we use a function, we need to define it. The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces. Function Definition
Syntax The basic syntax is shown here. <script type = "text/ javascript "> <!— function functionname (parameter-list) { Statements }//--> </script>
Example Try the following example. It defines a function called sayHello that takes no parameters − <script type = "text/ javascript "> <!--function sayHello () { alert("Hello there"); }//--> </script>
Calling a Function To invoke a function somewhere later in the script, you would simply need to write the name of that function as shown in the following code <html><head> <script type = "text/ javascript "> function sayHello () { document.write ("Hello there!"); } </script> </head>
<body> <p>Click the following button to call the function</p> <form> <input type = "button" onclick = " sayHello ()" value = "Say Hello"> </form> <p>Use different text in write method and then try...</p> </body> </html>
The JavaScript string is an object that represents a sequence of characters. There are 2 ways to create string in JavaScript By string literal By string object (using new keyword) String in JavaScript
1) By string literal The string literal is created using double quotes. The syntax of creating string using string literal is given below: var stringname ="string value";
2) By string object (using new keyword) The syntax of creating string object using new keyword is given below: var stringname =new String("string literal");
Methods Description charAt () It provides the char value present at the specified index. concat () It provides a combination of two or more strings. search() It searches a specified regular expression in a given string and returns its position if a match occurs. replace() It replaces a given string with the specified replacement. toLowerCase () It converts the given string into lowercase letter. toUpperCase () It converts the given string into uppercase letter. trim() It trims the white space from the left and right side of the string. JavaScript String Methods
The JavaScript date object can be used to get year, month and day. You can display a timer on the webpage by the help of JavaScript date object. Date in Javascript
Methods Description getDate () It returns the integer value between 1 and 31 that represents the day for the specified date on the basis of local time. getDay () It returns the integer value between 0 and 6 that represents the day of the week on the basis of local time. getFullYears() It returns the integer value that represents the year on the basis of local time. getHours() It returns the integer value between 0 and 23 that represents the hours on the basis of local time. getMilliseconds() It returns the integer value between 0 and 999 that represents the milliseconds on the basis of local time. getMinutes() It returns the integer value between 0 and 59 that represents the minutes on the basis of local time. getMonth() It returns the integer value between 0 and 11 that represents the month on the basis of local time. getSeconds() It returns the integer value between 0 and 60 that represents the seconds on the basis of local time. JavaScript Date Methods
The JavaScript math object provides several constants and methods to perform mathematical operation JavaScript Math
Methods Description abs() It returns the absolute value of the given number. cos () It returns the cosine of the given number. floor() It returns largest integer value, lower than or equal to the given number. max() It returns maximum value of the given numbers. min() It returns minimum value of the given numbers. pow() It returns value of base to the power of exponent. round() It returns closest integer value of the given number. Sqrt () It is used to return the square root of a number. JavaScript Math Methods
The window object represents a window in browser. An object of window is created automatically by the browser. The window object in JavaScript represents the browser's window. It provides various event handlers that allow you to respond to different events that occur within the window or the document it contains. Here are some common event handlers associated with the window object: Window in Javascript
onload : This event handler is triggered when the entire page (including all images, scripts, etc.) has finished loading. onunload : This event handler is triggered just before the user navigates away from the page (e.g., by closing the browser window or navigating to a different URL). onbeforeunload : Similar to onunload , this event handler is triggered just before the user navigates away from the page. It can be used to prompt the user with a confirmation dialog to confirm leaving the page.
onresize : This event handler is triggered when the window is resized. onscroll : This event handler is triggered when the user scrolls the window. onkeydown , onkeyup , onkeypress : These event handlers are triggered when the user presses a key, releases a key, or presses a key that produces a character respectively.
The change in the state of an object is known as an Event . In html, there are various events which represents that some activity is performed by the user or by the browser. JavaScript Events
Event Performed Event Handler Description click onclick When mouse click on an element mouseover onmouseover When the cursor of the mouse comes over the element mouseout onmouseout When the cursor of the mouse leaves an element mousedown onmousedown When the mouse button is pressed over the element mouseup onmouseup When the mouse button is released over the element mousemove onmousemove When the mouse movement takes place. Mouse events:
Event Performed Event Handler Description Keydown & Keyup onkeydown & onkeyup When the user press and then release the key Keyboard events:
Event Performed Event Handler Description focus onfocus When the user focuses on an element submit onsubmit When the user submits the form blur onblur When the focus is away from a form element change onchange When the user modifies or changes the value of a form element Form events:
<!DOCTYPE html> <html lang=" en "> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Focus Form Element</title> </head> <body> <form> <label for="username">Username:</label> <input type="text" id="username" name="username"> < br >< br > <label for="password">Password:</label> <input type="password" id="password" name="password"> </form> <script> // Focus on the username input when the page loads window.onload = function() { document.getElementById ("username").focus(); }; </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Submit Form Element</title> </head> <body> <form id="myForm" action="/submit-url" method="post"> <label for="username">Username:</label> <input type="text" id="username" name="username"> <br><br> <label for="password">Password:</label> <input type="password" id="password" name="password"> <br><br> <button type="button" onclick="submitForm()">Submit</button> </form> <script> function submitForm() { // Get the form element var form = document.getElementById("myForm"); // Submit the form form.submit(); } </script> </body> </html>
<!DOCTYPE html> <html lang=" en "> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Blur Form Element</title> </head> <body> <form> <label for="username">Username:</label> <input type="text" id="username" name="username"> < br >< br > <label for="password">Password:</label> <input type="password" id="password" name="password"> < br >< br > <button type="button" onclick=" blurElement ()">Blur Username</button> </form> <script> function blurElement () { // Get the username input element var usernameInput = document.getElementById ("username"); // Remove focus from the username input usernameInput.blur (); } </script> </body> </html>
<!DOCTYPE html> <html lang=" en "> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> onchange Event Example</title> </head> <body> <label for=" color ">Select a color :</label> <select id=" color " onchange =" showSelectedColor ()"> <option value="red">Red</option> <option value="blue">Blue</option> <option value="green">Green</option> <option value="yellow">Yellow</option> </select> <p id=" selectedColor "></p> <script> function showSelectedColor () { var colorSelect = document.getElementById (" color "); var selectedColor = colorSelect.value ; var selectedColorText = colorSelect.options [ colorSelect.selectedIndex ].text; document.getElementById (" selectedColor "). innerText = "You selected: " + selectedColorText + " (" + selectedColor + ")"; } </script> </body> </html>