Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
16 views

Javascript 3

Uploaded by

fizasm33
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Javascript 3

Uploaded by

fizasm33
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

What is JavaScript?

JavaScript (JS) is a text-based programming language used both on the client and server sides,
allowing you to make web pages interactive. It is one of the three core technologies of World
Wide Web content production (along with HTML and CSS).
JavaScript is used to make web pages interactive. It can add animations, control multimedia,
display dynamic content, and more. JavaScript is also used in game development, mobile app
development, and server-side programming.
JavaScript is a high-level, interpreted programming language. This means that it is relatively
easy to learn and use and that it does not need to be compiled before it can be
executed. JavaScript is also a dynamic language, which means that it can be changed while it is
running.
JavaScript is a very versatile language. It can be used to create various web applications, from
simple games to complex web-based applications. JavaScript is also used in a variety of other
non-web applications, such as game development, mobile app development, and server-side
programming.
Things that you can do with JavaScript:

• Add animations to your web pages


• Control multimedia, such as video and audio
• Display dynamic content, such as news feeds and stock quotes
• Create interactive forms
• Validate user input
• Send and receive data from a server
• Create games
• Develop mobile apps
• Write server-side code

Embedding JavaScript in a web page

Embedding JavaScript in a web page refers to the process of integrating JavaScript code directly
into the HTML document of a webpage. This integration allows the JavaScript code to be
executed within the context of the webpage, enabling functionalities such as interactivity,
dynamic content manipulation, form validation, and more.
There are three ways to embed JavaScript in a web page:

• Inline JavaScript: This is the simplest way to embed JavaScript in a web page. You can
simply write your JavaScript code between a pair of <script> and </script> tags. For
example:

Code
<script>
alert("Hello,world!");
</script>

This code will display an alert box with the message "Hello, world!" when the page loads.

• External JavaScript: You can also embed JavaScript in a web page by linking to an
external JavaScript file. To do this, you use the <script> tag with the src attribute. For
example

Code
<script src="my-script.js"></script>

This code will load the JavaScript file my-script.js when the page loads.

• Event Handlers: You can also use JavaScript to handle events on a web page. For
example, you can use JavaScript to display an alert box when a user clicks on a
button. To do this, you use the onclick attribute on the button tag. For example:

Code
<button onclick="alert('Hello, world!')">Click Me!</button>

This code will display an alert box with the message "Hello, world!" when the user clicks
on the Button.

Where to Put JavaScript Code


You can put JavaScript code in the <head> or <body> section of your HTML
document. However, it is generally recommended to put JavaScript code in
the <body> section. This is because JavaScript code can slow down the loading of your page, so
it is best to put it at the end of the page so that the rest of the page can load first.
What do you mean by RollOvers?
"Rollovers" typically refer to interactive effects triggered when a user hovers over or rolls their
cursor over an element on a webpage, such as an image or a button. JavaScript is commonly used
to implement rollover effects by dynamically changing the appearance or behavior of the
element in response to user interaction.
For example, a rollover effect might involve changing the color, size, or position of an element
when the user hovers over it. This can be achieved by using JavaScript event handlers, such as
the `mouseover` and `mouseout` events, to detect when the user interacts with the element and
then modify its properties accordingly.
Creating Rollovers using HTML
<HTML>
<head></head>
<Body>
<textarea rows=”2″ cols=”50″ name=”rollovertext”
onmouseover=”this.value=’Whatisrollover?'”
onmouseout=”this.value=’Rollover means a webpage changes when the user moves his or
her mouseover an object on the page'”>
</textarea>
</body>
</html>

Create a rollover effect that can change the color of its text using the style attribute.
<p
onmouseover=”this.style.color=’red'”
onmouseout=”this.style.color=’blue'”>
Move the mouse over this text to change its color to red. Move the mouse away to
change the text color to blue.
</p>

Preloading images in JavaScript


Preloading images in JavaScript refers to loading images into the browser's cache before they are
actually needed, typically done in scenarios where you anticipate that an image will be displayed
later on a webpage. This technique can help improve the user experience by reducing the delay
when displaying an image, especially in situations where the image file is large or hosted on a
slow server.
Preloading images in web development offers several benefits:
1. Improved User Experience: Preloading images reduces the delay between navigating to a
webpage and seeing images load. Users perceive faster load times, leading to a smoother
browsing experience.
2. Reduced Latency: By loading images into the browser cache before they're needed, you
mitigate the latency associated with fetching images from a server when they are required. This
is particularly beneficial for large images or slow server connections.
3. Optimized Performance: Preloading images can optimize the performance of your website
by ensuring that resources are available when needed. This can lead to faster rendering times and
smoother page interactions.
4. Enhanced Accessibility: Users with slower internet connections or limited bandwidth benefit
from preloaded images because they reduce the amount of time spent waiting for content to load.
5. Consistent Display: Preloading images ensures that images are ready to be displayed when
needed, preventing any flickering or layout shifts that can occur when images are loaded
dynamically.
6. Caching Benefits: Preloaded images are stored in the browser cache, which means they may
be reused across multiple pages or sessions, further improving load times for subsequent visits to
your website.
7. Better SEO: Faster load times can positively impact your website's search engine rankings, as
search engines like Google prioritize websites that provide a better user experience.
Code for Image Preloading.
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<p>onload Event</p>
<img id="img1" src="cat1.jpeg">
<img id="img2" src="cat2.jpeg" >
<script>
const img1 = document.getElementById("img1");
const img2 = document.getElementById("img2");
img1.addEventListener("load", function(){
alert("first image is loaded");
});
img2.addEventListener("load", function(){
alert("second image is loaded");
})
</script>
</body>
</html>

Comparison in JavaScript
Comparison in JavaScript refers to the process of evaluating two values or expressions to
determine whether they are equal, not equal, greater than, less than, greater than or equal to, or
less than or equal to. This is done using comparison operators, which return a Boolean value of
true or false.

There are six comparison operators in JavaScript:

• ==: Equal to
• !=: Not equal to
• ===: Strictly equal to
• !==: Strictly not equal to
• >: Greater than
• <: Less than
• >=: Greater than or equal to
• <=: Less than or equal to

The first two operators, == and !=, perform type coercion before comparing the values. This
means that they will try to convert the values to the same type before comparing them. For
example, if you compare a number to a string, the string will be converted to a number before the
comparison is made.
The next two operators, === and !==, perform strict equality comparisons. This means that they
will only return true if the values are the same type and value. For example, the following code
will return false, because the two values are different types:

JavaScript
1 === "1" // false

The last two operators, > and <, compare the values based on their order. Numbers are compared
numerically, and strings are compared lexicographically. For example, the following code will
return true, because the number 10 is greater than the number 5:

JavaScript
10 > 5 // true
Comparison operators are often used in conditional statements to control the flow of a
program. For example, the following code will print "The number is greater than 10" if the value
of the variable number is greater than 10:

JavaScript
if(number>10){
console.log("The number is greater than 10");
}

Comparison operators can also be used in expressions to create more complex comparisons. For
example, the following code will return true if the value of the variable number is greater than 10
and less than 20:

JavaScript
10 < number < 20 // true

Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Comparisons</title>
</head>
<body>
<h1>JavaScript Comparisons</h1>
<div id="output"></div>

<script>
// JavaScript code for comparisons
document.addEventListener("DOMContentLoaded", function() {
// Define variables
let a = 5;
let b = 10;
let c = 5;
let d = "5";

// Prepare output
let output = "";

// Equality comparisons
output += "<h2>Equality comparisons:</h2>";
output += "a == c: " + (a == c) + "<br>"; // true (loose equality, value comparison)
output += "a === c: " + (a === c) + "<br>"; // true (strict equality, value and type
comparison)
output += "a == d: " + (a == d) + "<br>"; // true (loose equality, type coercion)
output += "a === d: " + (a === d) + "<br><br>"; // false (strict equality, different
types)

// Relational comparisons
output += "<h2>Relational comparisons:</h2>";
output += "a < b: " + (a < b) + "<br>"; // true
output += "a <= c: " + (a <= c) + "<br>"; // true
output += "a > b: " + (a > b) + "<br>"; // false
output += "b >= c: " + (b >= c) + "<br><br>"; // true

// Logical comparisons
output += "<h2>Logical comparisons:</h2>";
output += "(a < 10) && (b > 5): " + ((a < 10) && (b > 5)) + "<br>"; // true
output += "(a < 10) || (b < 5): " + ((a < 10) || (b < 5)) + "<br>"; // true
output += "!(a === b): " + (!(a === b)) + "<br>"; // true

// Display output
document.getElementById("output").innerHTML = output;
});
</script>
</bodyc>
</html>
Built-in functions in JavaScript
Built-in functions in JavaScript are functions that are provided by the JavaScript language itself,
available for use without needing to define them explicitly. These functions are part of the
JavaScript runtime environment and can be accessed directly.

JavaScript comes with a rich set of built-in functions that perform common tasks such as
manipulating strings, working with arrays, performing mathematical operations, interacting with
the browser's Document Object Model (DOM), and more.
Here are some examples of built-in functions in JavaScript:
1. String Functions:
- `toUpperCase()`: Converts a string to uppercase.
- `substring()`: Extracts a part of a string.
- `indexOf()`: Returns the index of the first occurrence of a specified value in a string.
2. Array Functions:
- `push()`: Adds one or more elements to the end of an array and returns the new length of the
array.
- `pop()`: Removes the last element from an array and returns that element.
- `forEach()`: Executes a provided function once for each array element.

3. Math Functions:
- `Math.random()`: Returns a pseudo-random number between 0 and 1.
- `Math.floor()`: Rounds a number down to the nearest integer.
- `Math.max()`: Returns the largest of zero or more numbers.

4. DOM Functions:
- `document.getElementById()`: Returns a reference to the element by its ID.
- `document.createElement()`: Creates a new HTML element.
- `addEventListener()`: Attaches an event handler to the specified element.

Pattern matching
Pattern matching in JavaScript is a programming paradigm that allows developers to match
values against a pattern and execute code based on the match. It is not a native feature of
JavaScript, but there are several ways to implement it.
One way to implement pattern matching in JavaScript is to use regular expressions. Regular
expressions are sequences of characters that define a search pattern. They can be used to search
for patterns in text and to replace text with other text.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pattern Matching Example</title>
</head>
<body>
<h1>Pattern Matching Example</h1>
<p id="output"></p>

<script>
// Example string
let text = "The quick brown fox jumps over the lazy dog.";

// Define a regular expression pattern to match the word "fox"


let pattern = /fox/;

// Test if the pattern matches the text


let isMatch = pattern.test(text);

// Find all occurrences of the pattern in the text


let matches = text.match(pattern);
// Display the results
let output = "Text: " + text + "<br>";
output += "Pattern: " + pattern + "<br>";
output += "Pattern matches: " + isMatch + "<br>";
output += "Matches found: " + matches + "<br>";

document.getElementById("output").innerHTML = output;
</script>
</body>
</html>

JavaScript Object
In JavaScript, objects are variables that can store many values. Objects are similar to real-world
objects, having properties and methods.

• Properties
are the values associated with an object. A JavaScript object is a collection of unordered
properties. Properties can usually be changed, added, and deleted, but some are read only.
• Methods
are functions that are defined inside objects. Methods are used to perform actions on the
object.
For example, a car object might have properties like color, make, and model. It might also have
methods like drive() and stop().
Objects are a fundamental part of JavaScript. They are used to store and organize data, and to
perform actions on that data.
Here is an example of a JavaScript object:

const car = {
color: "red",
make: "Toyota",
model: "Camry",
drive: function() {
console.log("The car is driving.");
},
stop: function() {
console.log("The car has stopped.");
}
};

This object has three properties: color, make, and model. It also has two methods: drive() and
stop().
To access a property of an object, you use the dot notation. For example, to access the color
property of the car object, you would use the following code:

JavaScript
const carColor = car.color;
To call a method of an object, you use the parentheses notation. For example, to call the drive()
method of the car object, you would use the following code:

JavaScript
car.drive();

Objects are a powerful tool in JavaScript. They allow you to store and organize data, and to
perform actions on that data flexibly and efficiently.

Code(working on console)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Object Example</title>
</head>
<body>
<h1>JavaScript Object Example</h1>

<script>
// Define a JavaScript object
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
email: "john@example.com",
address: {
street: "123 Main St",
city: "Anytown",
country: "USA"
},
hobbies: ["reading", "coding", "hiking"],
sayHello: function() {
return "Hello, my name is " + this.firstName + " " + this.lastName;
}
};

// Accessing object properties


console.log("First Name:", person.firstName);
console.log("Age:", person.age);
console.log("City:", person.address.city);
console.log("Hobbies:", person.hobbies);

// Calling object method


console.log(person.sayHello());
</script>
</body>
</html>

Interacting with users in JavaScript


Interacting with users in JavaScript can be done in various ways, such as displaying messages,
taking input, responding to events, and updating the content of web pages dynamically. Here's
how you can perform some common interactions with users using JavaScript:

1. Displaying Messages:
You can use `alert()`, `confirm()`, and `prompt()` functions to display messages or dialogs:
javascript
// Alert dialog
alert("Hello, this is an alert message!");

// Confirm dialog
let result = confirm("Are you sure you want to proceed?");
if (result) {
console.log("User confirmed!");
} else {
console.log("User cancelled!");
}

// Prompt dialog
let name = prompt("Please enter your name:", "");
console.log("Hello, " + name + "!");

2. Event Handling:
You can respond to user interactions, such as clicks, key presses, mouse movements, etc., using
event listeners:
html
<button id="myButton">Click Me</button>

<script>
// Event listener for button click
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});
</script>
3. Updating HTML Content:
You can dynamically update the content of HTML elements:
Html
<p id="demo">This is some text.</p>
<script>
// Update content of paragraph
document.getElementById("demo").innerHTML = "This is updated text.";
</script>

4. Taking Input:
You can take input from users using forms and handle it using JavaScript:

html
<form id="myForm">
<input type="text" id="nameInput" placeholder="Enter your name">
<button type="submit">Submit</button>
</form>

<script>
// Event listener for form submission
document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault(); // Prevent default form submission
let name = document.getElementById("nameInput").value;
alert("Hello, " + name + "!");
});
</script>

These are just a few examples of how you can interact with users using JavaScript. Depending
on your application's requirements, you can combine these techniques to create rich and
interactive user experiences on the web.

Conversion calculator in JavaScript


code
<html>
<head>
<title>Length Converter</title>
</head>
<body>

<h2>Length Converter</h2>

<!-- Kilometers to Meters Converter -->


<h3>Kilometers to Meters</h3>
<p>Type a value in the Kilometers field to convert the value to Meters:</p>
<p>
<label>Kilometers</label>
<input id="inputKilometers" type="number" placeholder="Kilometers"
oninput="convertKilometersToMeters(this.value)">
</p>
<p>Meters: <span id="outputMeters"></span></p>

<!-- Meters to Kilometers Converter -->


<h3>Meters to Kilometers</h3>
<p>Type a value in the Meters field to convert the value to Kilometers:</p>
<p>
<label>Meters</label>
<input id="inputMeters" type="number" placeholder="Meters"
oninput="convertMetersToKilometers(this.value)">
</p>
<p>Kilometers: <span id="outputKilometers"></span></p>

<script>
// Function to convert Kilometers to Meters
function convertKilometersToMeters(valNum) {
document.getElementById("outputMeters").innerHTML = valNum * 1000;
}

// Function to convert Meters to Kilometers


function convertMetersToKilometers(valNum) {
document.getElementById("outputKilometers").innerHTML = valNum / 1000;
}
</script>

</body>
</html>

Form Checking
Form validation is the process of checking user input for errors before submitting it to a
server. This is important because it helps to ensure that the data is accurate and complete and that
it can be processed correctly.
There are several different ways to validate forms in JavaScript. One common approach is to use
regular expressions to check for patterns in the input. For example, you could use a regular
expression to check that an email address is in a valid format.
Another approach to form validation is to use the built-in validation features of
HTML5. HTML5 provides several attributes that can be used to specify the type of data that is
expected in a field and to provide feedback to the user if the input is invalid.
Form validation is an important part of any web application. By taking the time to validate your
forms, you can help to ensure that your data is accurate and complete and that your users have a
positive experience.

Here are some of the benefits of using JavaScript for form validation:

• Improved data accuracy:


JavaScript form validation can help to ensure that the data submitted by users is accurate
and complete. This is important for businesses that rely on this data to make decisions.
• Enhanced security:
JavaScript form validation can help to prevent malicious users from submitting harmful data
or code. This can help to protect your website and users from attacks.
• Better user experience:
JavaScript form validation can improve the user experience by preventing users from
submitting forms with errors. This can save users time and frustration

Overall, JavaScript form validation is a valuable tool that can help to improve the accuracy,
security, and user experience of your website.
code
<html>
<head>
<title>Form Validation</title>
<style>
.error {
color: red;
}
</style>
</head>
<body>

<h2>Registration Form</h2>

<form id="registrationForm" onsubmit="return validateForm()">


<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<span id="usernameError" class="error"></span><br>

<label for="email">Email:</label><br>
<input type="email" id="email" name="email"><br>
<span id="emailError" class="error"></span><br>

<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br>

<label for="confirmPassword">Confirm Password:</label><br>


<input type="password" id="confirmPassword" name="confirmPassword"><br>
<span id="passwordError" class="error"></span><br>

<input type="submit" value="SUBMIT">


</form>
<script>
function validateForm() {
let username = document.getElementById("username").value;
let email = document.getElementById("email").value;
let password = document.getElementById("password").value;
let confirmPassword = document.getElementById("confirmPassword").value;

// Reset error messages


document.getElementById("usernameError").innerHTML = "";
document.getElementById("emailError").innerHTML = "";
document.getElementById("passwordError").innerHTML = "";

// Username validation
if (username === "") {
document.getElementById("usernameError").innerHTML = "Username is required";
return false;
}

// Email validation
if (email === "") {
document.getElementById("emailError").innerHTML = "Email is required";
return false;
} else if (!validateEmail(email)) {
document.getElementById("emailError").innerHTML = "Invalid email format";
return false;
}

// Password validation
if (password === "") {
document.getElementById("passwordError").innerHTML = "Password is required";
return false;
} else if (password !== confirmPassword) {
document.getElementById("passwordError").innerHTML = "Passwords do not
match";
return false;
}

return true; // Form submission allowed


}

function validateEmail(email) {
// Regular expression for validating email format
let emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
</script>

</body>
</html>

Testing and Debugging in JavaScript


In JavaScript, testing and debugging are two different processes that are used to ensure the
quality of code. Testing is the process of verifying that the code meets all of its
requirements. This can be done by manually testing the code, or by using automated testing
tools. Debugging is the process of finding and fixing errors in the code. This can be done using a
variety of tools and techniques, such as using a debugger to step through the code line by line, or
by using print statements to output the values of variables.
Here are some of the key differences between testing and debugging in JavaScript:

Testing

• Testing is a proactive process that is used to prevent errors from occurring in the first
place.
• Testing is typically done by a separate team of testers, who are not responsible for writing
the code.
• Testing can be done manually, or by using automated testing tools.
• The goal of testing is to verify that the code meets all of its requirements.
Debugging

• Debugging is a reactive process that is used to find and fix errors that have already
occurred.
• Debugging is typically done by the developers who wrote the code.
• Debugging is done using a variety of tools and techniques, such as using a debugger to
step through the code line by line, or by using print statements to output the values of
variables.
• The goal of debugging is to fix errors in the code so that it works as expected.
Both testing and debugging are essential for ensuring the quality of JavaScript code. By
following a disciplined approach to testing and debugging, developers can help to ensure that
their code is reliable and meets all of its requirements.

Server Side Scripting and Client Side Scripting


1. Client-side scripting :
Web browsers execute client-side scripting. It is used when browsers have all the code. Source
code is used to transfer from the webserver to the user’s computer over the internet and run
directly on browsers. It is also used for validations and functionality for user events.
It allows for more interactivity. It usually performs several actions without going to the user. It
cannot be used to connect to databases on a web server. These scripts cannot access the file
system that resides in the web browser. Pages are altered based on the user’s choice. It can also
be used to create “cookies” that store data on the user’s computer.
2. Server-side scripting :
Web servers are used to execute server-side scripting. They are used to create dynamic pages. It
can also access the file system residing at the webserver. A server-side environment that runs on
a scripting language is a web server.
Scripts can be written in any of the many server-side scripting languages available. It is used to
retrieve and generate content for dynamic pages. It is used to require to download plugins. In this
load times are generally faster than client-side scripting. When you need to store and retrieve
information a database will be used to contain data. It can use huge resources of the server. It
reduces client-side computation overhead. The server sends pages to the request of the
user/client.
Difference between client-side scripting and server-side scripting :

Client-side scripting Server-side scripting

The source code is not visible to the user because its


output
Source code is visible to the user.
of the server-side side is an HTML page.

Its main function is to provide the Its primary function is to manipulate and provide
requested output to the end user. access to the respective database as per the request.

In this, any server-side technology can be used and


It usually depends on the browser and it does not
its version. depend on the client.

It runs on the user’s computer. It runs on the web server.

There are many advantages linked with


The primary advantage is its ability to highly
this like faster.
customize, response
response times, a more interactive
requirements, access rights based on user.
application.

It does not provide security for data. It provides more security for data.

It is a technique used in web It is a technique that uses scripts on the webserver


development in which scripts run on the to produce a response that is customized for each
client’s browser. client’s request.

HTML, CSS, and javascript are used. PHP, Python, Java, Ruby are used.

No need of interaction with the server. It is all about interacting with the servers.

It reduces load on processing unit of the


It surge the processing load on the server.
server.

You might also like