2. 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.
3. 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.
4. 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
5. 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.
6. 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.
7. 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);
8. 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");
9. 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
10. The <script> Tag
In HTML, JavaScript code is inserted between <script>
and </script> tags.
11. 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.*/
12. Using var (2015)
Using let (after 2015)
Using const
Using nothing
13. 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
14.
15.
16.
17.
18.
19. An expression is a combination of values,
variables, and operators, which computes to a
value
5*10
X+40
"John" + " " + "Doe"
24. Arithmetic Operators
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
25. 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
26. 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
27. 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
28. Operato
r
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
29. 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.
30. 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.
33. Converting Strings to Numbers
Converting Numbers to Strings
Converting Dates to Numbers
Converting Numbers to Dates
Converting Booleans to Numbers
Converting Numbers to Booleans
34. The global method Number() converts a
variable (or a value) into a number.
35.
36. The global method String() can convert
numbers to strings.
It can be used on any type of numbers,
literals, variables, or expressions:
37.
38.
39.
40.
41.
42. 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)
43.
44. 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
}
45. 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
}
46. 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
}
48. 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.
49. Syntax
The syntax of while loop in JavaScript is as follows −
while (expression)
{
Statement(s) to be executed if expression is true
}
50. 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);
51. 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.
52. 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
}
53. 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.
54. Syntax
The basic syntax is shown here.
<script type = "text/javascript">
<!—
function functionname(parameter-list)
{
Statements
}//-->
</script>
55. 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>
56. 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>
57. <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>
58. 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)
59. 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";
60. 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");
61. 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.
62. 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.
63. 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.
64. The JavaScript math object provides several constants
and methods to perform mathematical operation
65. 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.
66. 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:
67. 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.
68. 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.
69.
70.
71. 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.
72. 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.
73. Event Performed
Event Handler Description
Keydown & Keyup
onkeydown &
onkeyup
When the user press
and then release the
key
74. 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
Client-side Script:
A client-side script refers to a program written in a scripting language (such as JavaScript) that accompanies an HTML document.
These scripts are executed on the client's machine, typically within a web browser, as opposed to being executed on the server.
The execution occurs when the HTML document loads in the browser or in response to specific events triggered by user actions, such as clicking a link or submitting a form.
Execution Timing:
The script can execute either when the HTML document initially loads or at a later time based on specific triggers or events.
For example, a script may execute immediately upon page load to perform initialization tasks, or it may wait for a user action like clicking a button to execute certain functionalities.
Independence from HTML:
HTML documents support the inclusion of scripts regardless of the scripting language used.
This means that HTML itself does not dictate the choice of scripting language; rather, it provides mechanisms (such as the <script> tag) for including and executing scripts.
Common scripting languages used with HTML include JavaScript, VBScript, and more recently, TypeScript.
Common Gateway Interface (CGI) programs are scripts or executable programs that handle the communication between a web server and external programs or databases. They are often used to generate dynamic content on web pages, such as processing form data, accessing databases, or performing other server-side tasks.
JavaScript is a high-level, interpreted programming language primarily used for creating dynamic and interactive content on web pages. Originally developed by Netscape, JavaScript has evolved into one of the most widely used languages for web development. Here are some key points about JavaScript:
Client-side scripting: JavaScript is primarily executed on the client side, meaning it runs in the user's web browser. This allows JavaScript to manipulate the content of web pages, respond to user interactions, and dynamically update the page without needing to communicate with the server.
Dynamic and interactive: JavaScript enables developers to create dynamic and interactive web experiences by allowing them to modify HTML and CSS, handle events such as mouse clicks and keyboard input, and perform actions like form validation and animations.
Versatile: While JavaScript is most commonly associated with web development, it is also used in other environments such as server-side development (with platforms like Node.js), mobile app development (using frameworks like React Native), and desktop application development (with tools like Electron).
The dot (.) is a CSS notation indicating that "highlight" is a class name. In CSS syntax, when you prefix a name with a dot (.), it signifies a class selector.
This line retrieves the element with the ID "demo" using document.getElementById("demo"), and then sets its innerHTML property to the value of x. This will display the value of x
In JavaScript, the Number() function is typically used to convert a value to a number. However, when attempting to convert the string '99 88"' to a number using the Number() function, it will return NaN because the string is not a valid number. The presence of non-numeric characters like space and double quotes makes it impossible to interpret the string as a valid number.
When you attempt to convert the string 'John" to a number using the Number() function in JavaScript, it will return NaN (Not a Number). This is because the string 'John" does not represent a valid numeric value. The Number() function in JavaScript is used to convert values to numbers, but it can only convert strings that represent valid numeric values (such as '123', '3.14', etc.). If the string contains non-numeric characters or cannot be interpreted as a number, the result of Number() will be NaN.
String(123)
This will return the string "123", as the number 123 is converted to its string representation.
String(100+23)
This will return the string "123", as the expression 100+23 evaluates to 123, which is then converted to its string representation.
In this example, when the page loads, the JavaScript code within the <script> tag is executed. It selects the username input element by its ID ("username") using document.getElementById("username"), then it calls the focus() method on this element to give it focus. As a result, the cursor will automatically be placed in the username input field when the page loads.
In this example, the form element has an ID of "myForm". When the button with the onclick attribute calls the submitForm() function, it grabs the form element using document.getElementById("myForm") and then calls the submit() method on it. This action triggers the submission of the form. The form submission will then follow the action specified in the form's action attribute, which in this case is set to "/submit-url", and the method specified in the method attribute, which is set to "post".
In this example, clicking the "Blur Username" button triggers the blurElement() function, which gets the username input element by its ID ("username") using document.getElementById("username"), and then calls the blur() method on it. This removes the focus from the username input field.
In this example, we have a <select> element with options for different colors. The onchange attribute is set to the function showSelectedColor(). When the user selects a different color from the dropdown, the showSelectedColor() function is triggered.
Inside the function:
We first get the <select> element using document.getElementById("color").
We retrieve the selected value using colorSelect.value, which represents the value of the selected <option>.
We also retrieve the text of the selected <option> using colorSelect.options[colorSelect.selectedIndex].text.
Finally, we update the content of the paragraph element with the id "selectedColor" to display the selected color and its corresponding value.