CSS Summer 22
CSS Summer 22
<p id="result"></p>
<script>
function checkPrime() {
// Get the entered number
let number = parseInt(document.getElementById("numberInput").value);
let isPrime = true;
</body>
</html>
<script>
document.getElementById("myButton").addEventListener("mouseup", function() {
document.getElementById("output").innerHTML = "Mouse button released!";
});
</script>
</body>
</html>
2. onblur Event
The onblur event is triggered when an element loses focus. This is commonly used for form elements
(like text inputs, textareas, or dropdowns) to detect when the user has finished interacting with a field and
moved focus to another element or clicked elsewhere on the page.
Key Points:
The onblur event is typically used for input validation or triggering an action when the user
moves away from a form field.
It can be useful in scenarios like checking for required fields, validating email formats, or saving
data when the user leaves a field.
Example Usage:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>onblur Event Example</title>
</head>
<body>
<script>
document.getElementById("emailInput").addEventListener("blur", function() {
let emailValue = document.getElementById("emailInput").value;
</body>
</html>
(a) Write a javascript program to validate user accounts for multiple set of user ID and password
(using swith case statement).
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Account Validation</title>
</head>
<body>
<label for="passwordInput">Password:</label>
<input type="password" id="passwordInput" placeholder="Enter Password">
<br><br>
<button onclick="validateUser()">Login</button>
<p id="result"></p>
<script>
function validateUser() {
// Get user input values
var userId = document.getElementById("userIdInput").value;
var password = document.getElementById("passwordInput").value;
var result = "";
case "user2":
if (password === "password2") {
result = "Welcome, User 2!";
} else {
result = "Invalid password for User 2.";
}
break;
case "admin":
if (password === "adminPass") {
result = "Welcome, Admin!";
} else {
result = "Invalid password for Admin.";
}
break;
default:
result = "Invalid User ID.";
break;
}
</body>
</html>
(d) Design a webpage that displays a form that contains an input for user name and password. User
is prompted to enter the input user name and password and password become value of the cookies.
Write the javascript function for storing the cookies.
Ans.
<html>
<head>
<script>
function storeCookie()
{
var pwd = document.getElementById('pwd').value
document.cookie = "Password=" + pwd + ";"
alert("Cookie Stored\n"+document.cookie);
}
</script>
</head>
<body>
<form name="myForm">
Enter Username <input type="text" id="uname"/><br/>
Enter Password <input type="password" id="pwd"/><br/>
<input type="button" value="Submit" onclick="storeCookie()"/>
<p id="panel"></p>
</form>
</body>
</html>
(a) Write a javascript program to create read, update and delete cookies.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cookie Management</title>
<script>
// Function to create or update a cookie
function setCookie(cname, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000)); // Set expiration date in milliseconds
let expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
alert("Cookie " + cname + " has been set.");
}
<button onclick="setCookie(document.getElementById('cookieName').value,
document.getElementById('cookieValue').value,
document.getElementById('expiryDays').value)">Create/Update Cookie</button>
<button onclick="checkCookie(document.getElementById('cookieName').value)">Read
Cookie</button>
<button onclick="deleteCookie(document.getElementById('cookieName').value)">Delete
Cookie</button>
</div>
<h3>Instructions:</h3>
<p>1. Enter a cookie name, value, and expiry days, then click **Create/Update Cookie** to set the
cookie.</p>
<p>2. Enter the cookie name and click **Read Cookie** to retrieve the cookie value.</p>
<p>3. Enter the cookie name and click **Delete Cookie** to remove the cookie.</p>
</body>
</html>
(c) Write a javascript program to calculate add, sub, multiplication and division of two number
(input from user). Form should contain two text boxes to input numbers of four buttons for
addition, subtraction, multiplication and division.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
</head>
<body>
<h1>Simple Calculator</h1>
<script>
function calculate(operation) {
// Get the input values from the textboxes
var num1 = parseFloat(document.getElementById("num1").value);
var num2 = parseFloat(document.getElementById("num2").value);
var result;
</body>
</html>
(d) State what is regular expression. Explain its meaning with the help of a suitable example.
Ans.Regular Expression:
A regular expression is very similar to a mathematical expression, except a
regular expression tells the browser how to manipulate text rather than numbers
by using special symbols as operators.
Example:
<html>
<body>
<script>
function myFunction() {
// input string
var str = "Good Morning!";
// searching string with modifier i
var n = str.search(/Morning/i);
document.write(n + '<br>');
// searching string without modifier i
var n = str.search(/Morning/);
document.write(n);
}
myFunction();
</script>
</body>
</html>
(c) Write a javascript program to validate email ID of the user using regular expression.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Email Validation</title>
<script>
// Function to validate email using a regular expression
function validateEmail() {
const email = document.getElementById("email").value;
// Regular expression for validating email
const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
</body>
</html>
(d)Write a javascript program to design HTML page with books information in abular format, use
rollovers to display the discount information.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Book Information</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
.discount {
display: none;
position: absolute;
background-color: yellow;
padding: 5px;
border: 1px solid #ccc;
border-radius: 4px;
z-index: 10;
}
</style>
</head>
<body>
<h1>Book Information</h1>
<table>
<thead>
<tr>
<th>Book Title</th>
<th>Author</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td onmouseover="showDiscount(event, '10% Off!')"
onmouseout="hideDiscount()">JavaScript: The Good Parts</td>
<td>Douglas Crockford</td>
<td>$29.99</td>
</tr>
<tr>
<td onmouseover="showDiscount(event, '15% Off!')" onmouseout="hideDiscount()">Clean
Code</td>
<td>Robert C. Martin</td>
<td>$34.99</td>
</tr>
<tr>
<td onmouseover="showDiscount(event, '20% Off!')" onmouseout="hideDiscount()">Eloquent
JavaScript</td>
<td>Marijn Haverbeke</td>
<td>$39.99</td>
</tr>
<tr>
<td onmouseover="showDiscount(event, '5% Off!')" onmouseout="hideDiscount()">The
Pragmatic Programmer</td>
<td>Andrew Hunt, David Thomas</td>
<td>$49.99</td>
</tr>
</tbody>
</table>
<script>
function showDiscount(event, discount) {
const tooltip = document.getElementById("discountTooltip");
tooltip.innerText = discount; // Set the discount text
tooltip.style.left = event.pageX + 'px'; // Position tooltip
tooltip.style.top = event.pageY + 'px'; // Position tooltip
tooltip.style.display = 'block'; // Show tooltip
}
function hideDiscount() {
const tooltip = document.getElementById("discountTooltip");
tooltip.style.display = 'none'; // Hide tooltip
}
</script>
</body>
</html>
(e)List ways of protecting your webpage and describe any one of them.
Ans.Ways of protecting Web Page:
1)Hiding your source code
2)Disabling the right MouseButton
3) Hiding JavaScript
4) Concealing E-mail address.
1) Hiding your source code
The source code for your web page—including your JavaScript—is stored in the
cache, the part of computer memory where the browser stores web pages that
were requested by the visitor. A sophisticated visitor can access the cache and
thereby gain access to the web page source code.
However, you can place obstacles in the way of a potential peeker. First, you can
disable use of the right mouse button on your site so the visitor can't access the
View Source menu option on the context menu. This hides both your HTML code
and your JavaScript from the visitor.
Nevertheless, the visitor can still use the View menu's Source option to display
your source code. In addition, you can store your JavaScript on your web server
instead of building it into your web page. The browser calls the JavaScript from
the web server when it is needed by your web page.
Using this method, the JavaScript isn't visible to the visitor, even if the visitor
views the source code for the web page.
2)Disabling the right MouseButton
The following example shows you how to disable the visitor's right mouse button
while the browser displays your web page. All the action occurs in the JavaScript
that is defined in the <head> tag of the web page.
The JavaScript begins by defining the BreakInDetected() function. This function
is called any time the visitor clicks the right mouse button while the web page is
displayed. It displays a security violation message in a dialog box whenever a
visitor clicks the right mouse button
The BreakInDetected() function is called if the visitor clicks any button other
than the left mouse button.
Example:
<html>
<head>
<title>Lockout Right Mouse Button</title>
<script language=JavaScript>
function BreakInDetected(){
alert('Security Violation')
return false
}
function NetscapeBrowser(e){
if (document.layers||
document.getElementById&&!document.all){
if (e.which==2||e.which==3){
BreakInDetected()
return false
}
}
}
function InternetExploreBrowser(){
if (event.button==2){
BreakInDetected()
return false
}
}
if (document.layers){
document.captureEvents(Event.MOUSEDOWN)
document.onmousedown=NetscapeBrowser()
}
else if (document.all&&!document.getElementById){
document.onmousedown=InternetExploreBrowser()
}
document.oncontextmenu=new Function(
"BreakInDetected();return false")
</script>
</head>
<body>
<table width="100%" border=0>
<tbody>
<tr vAlign=top>
<td width=50>
<a>
<ing height=92 src="rose.jpg"
width=70 border=0
onmouseover="src='rose1.jpg'"
onmouseout="src='rose.jpg'">
</a>
</td>
<td>
<img height=1 src="" width=10>
</td>
<td>
<a>
<cTypeface:Bold><u> Rose Flower</U></b>
</a>
</font><font face="arial, helvetica, sans-serif"
size=-1><BR>Rose Flower
</td>
</tr>
</tbody>
</table>
</body>
</html>
3) Hiding JavaScript
You can hide your JavaScript from a visitor by storing it in an external fi le on
your web server. The external fi le should have the .js fi le extension. The browser
then calls the external file whenever the browser encounters a JavaScript element
in the web page. If you look at the source code for the web page, you'll see
reference to the external .js fi le, but you won't see the source code for the
JavaScript.
The next example shows how to create and use an external JavaScript file. First
you must tell the browser that the content of the JavaScript is located in an
external
file on the web server rather than built into the web page. You do this by assigning
the fi le name that contains the JavaScripts to the src attribute of the <script>
tag, as shown here:
<script src="MyJavaScripts.js"
language="Javascript" type="text/javascript">
Next, you need to defi ne empty functions for each function that you define in the
external JavaScript fi le.
<html >
<head>
<title>Using External JavaScript File</title>
<script src="myJavaScript.js" language="Javascript" type="text/javascript">
function OpenNewWindow(book) {
}
</script>
</head>
<body>
<tablewidth="100%" border=0>
<tbody>
<tr vAlign=top>
<td width=50>
<a>
<img height=92 src="rose.jpg" width=70 border=0 name='cover'>
</a>
</td>
<td>
<img height=1 src="" width=10>
</td>
<td>
<a onmouseover="OpenNewWindow(1)" onmouseout="MyWindow.close()">
<b><u>Rose </u></b>
</a>
<br>
<a onmouseover="OpenNewWindow(2)" onmouseout="MyWindow.close()">
<b><u>Sunflower</U></b>
</a>
<br>
<A onmouseover="OpenNewWindow(3)" onmouseout="MyWindow.close()">
<b><u>Jasmine </u></b>
</a>
</td>
</tr>
</tbody>
</table>
</body>
</html>
The final step is to create the external JavaScript fi le. You do this by placing all
function definitions into a new fi le and then saving the fi le using the .js
extension.
MyJavaScript.js file:
function OpenNewWindow(book) {
if (book== 1)
{
document.cover.src='rose.jpg'
MyWindow = window.open('', 'myAdWin', 'titlebar=0 status=0, toolbar=0,
location=0, menubar=0, directories=0, resizable=0, height=50,
width=150,left=500,top=400')
MyWindow.document.write( 'Rose flower')
}
if (book== 2)
{
document.cover.src='sunflower.jpeg'
MyWindow = window.open('', 'myAdWin', 'titlebar=0 status=0, toolbar=0,
location=0, menubar=0, directories=0, resizable=0, height=50,
width=150,left=500,top=500')
MyWindow.document.write( 'sunflower flower')
}
if (book== 3)
{
document.cover.src='jasmine.gif'
MyWindow = window.open('', 'myAdWin', 'titlebar=0
status=0, toolbar=0, location=0, menubar=0, directories=0, resizable=0,
height=50,
width=150,left=500,top=600')
MyWindow.document.write( 'Jasmine Flower')
}
}
After you create the external JavaScript fi le, defi ne empty functions for each
function that is contained in the external JavaScript fi le, and reference the
external
JavaScript fi le in the src attribute of the <script> tag, you're all set.
4) Concealing E-mail address:
Many of us have endured spam at some point and have probably blamed every
merchant we ever patronized for selling our e-mail address to spammers. While
e-mail addresses are commodities, it's likely that we ourselves are the culprits
who invited spammers to steal our e-mail addresses.
Here's what happens: Some spammers create programs called bots that surf the
Net looking for e-mail addresses that are embedded into web pages, such as those
placed there by developers to enable visitors to contact them. The bots then strip
these e-mail addresses from the web page and store them for use in a spam attack.
This technique places developers between a rock and a hard place. If they place
their e-mail addresses on the web page, they might get slammed by spammers. If
they don't display their e-mail addresses, visitors will not be able to get in touch
with the developers.
The solution to this common problem is to conceal your e-mail address in the
source code of your web page so that bots can't fi nd it but so that it still appears
on the web page. Typically, bots identify e-mail addresses in two ways: by the
mailto: attribute that tells the browser the e-mail address to use when the visitor
wants to respond to the web page, and by the @ sign that is required of all e-mail
addresses. Your job is to confuse the bots by using a JavaScript to generate the
e-mail address dynamically. However, you'll still need to conceal the e-mail
address in your JavaScript, unless the JavaScript is contained in an external
JavaScript file, because a bot can easily recognize the mailto: attribute and the @
sign in a JavaScript.
Bots can also easily recognize when an external fi le is referenced. To conceal an
e-mail address, you need to create strings that contain part of the e-mail address
and then build a JavaScript that assembles those strings into the e-mail address,
which is then written to the web page.
The following example illustrates one of many ways to conceal an e-mail address.
It also shows you how to write the subject line of the e-mail. We begin by
creating four strings:
• The first string contains the addressee and the domain along with symbols &, *,
and _ (underscore) to confuse the bot.
• The second and third strings contain portions of the mailto: attribute name.
Remember that the bot is likely looking for mailto:.
• The fourth string contains the subject line. As you'll recall from your HTML
training, you can generate the TO, CC, BCC, subject, and body of an e-mail from
within a web page.
You then use these four strings to build the e-mail address. This process starts by
using the replace() method of the string object to replace the & with the @ sign
and the * with a period (.). The underscores are replaced with nothing, which is
the
same as simply removing the underscores from the string.
All the strings are then concatenated and assigned to the variable b, which is then
assigned the location attribute of the window object. This calls the e-mail program
on the visitor's computer and populates the TO and Subject lines with the strings
generated by the JavaScript.
<html>
<head>
<title>Conceal Email Address</title>
<script>
function CreateEmailAddress(){
var x = manish*c_o_m'
var y = 'mai'
var z = 'lto'
var s = '?subject=Customer Inquiry'
x = x.replace('&','@')
x = x.replace('*','.')
x = x.replace('_','')
x = x.replace('_','')
var b = y + z +':'+ x + s
window.location=b
}
-->
</script>
</head>
<body>
<input type="button" value="Help"
onclick="CreateEmailAddress()">
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Palindrome Checker</title>
<script>
// Function to check if a string is a palindrome
function isPalindrome(str) {
// Remove non-alphanumeric characters and convert to lowercase
let cleanedStr = str.toLowerCase().replace(/[^a-z0-9]/g, '');
(b) Develop javascript to convert the given character to unicode and vice-versa.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Character and Unicode Converter</title>
<script>
// Function to convert character to Unicode
function charToUnicode() {
const charInput = document.getElementById("charInput").value;
if (charInput.length === 0) {
alert("Please enter a character.");
return;
}
const unicodeValue = charInput.charCodeAt(0); // Get Unicode value of the first character
document.getElementById("unicodeOutput").innerText = "Unicode: " + unicodeValue;
}
<div>
<h3>Convert Unicode to Character</h3>
<label for="unicodeInput">Enter Unicode:</label><br>
<input type="text" id="unicodeInput" required><br>
<button onclick="unicodeToChar()">Convert to Character</button>
<p id="charOutput"></p>
</div>
</body>
</html>
(c) Write a javascript program to create a slide show with the group of six images, also simulate the
next and previous transition between slides in your javascript.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Slideshow</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 20px;
}
#slideshow {
width: 600px;
height: 400px;
margin: auto;
overflow: hidden;
position: relative;
}
#slideshow img {
width: 100%;
height: auto;
display: none; /* Initially hide all images */
}
#slideshow img.active {
display: block; /* Show active image */
}
.button {
padding: 10px 15px;
margin: 5px;
cursor: pointer;
background-color: #007BFF;
color: white;
border: none;
border-radius: 5px;
}
.button:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<h1>Image Slideshow</h1>
<div id="slideshow">
<img src="https://via.placeholder.com/600x400.png?text=Image+1" class="active">
<img src="https://via.placeholder.com/600x400.png?text=Image+2">
<img src="https://via.placeholder.com/600x400.png?text=Image+3">
<img src="https://via.placeholder.com/600x400.png?text=Image+4">
<img src="https://via.placeholder.com/600x400.png?text=Image+5">
<img src="https://via.placeholder.com/600x400.png?text=Image+6">
</div>
<br>
<button class="button" onclick="prevSlide()">Previous</button>
<button class="button" onclick="nextSlide()">Next</button>
<script>
let currentSlide = 0; // Keep track of the current slide
const slides = document.querySelectorAll('#slideshow img'); // Select all images in the slideshow
function showSlide(index) {
// Hide all slides
slides.forEach((slide) => {
slide.classList.remove('active');
});
// Show the current slide
slides[index].classList.add('active');
}
function nextSlide() {
currentSlide = (currentSlide + 1) % slides.length; // Move to the next slide
showSlide(currentSlide);
}
function prevSlide() {
currentSlide = (currentSlide - 1 + slides.length) % slides.length; // Move to the previous slide
showSlide(currentSlide);
}
</script>
</body>
</html>
(a) Write a javascript to open a new window and the new window is having two frames. One frame
containing buthon as “click here !”, and after clicking this button an image should open in the
second frame of that child window.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Main Window</title>
<script>
function openNewWindow() {
// Open a new window
const newWindow = window.open("", "newWindow", "width=600,height=400");
<h2>Main Window</h2>
<button onclick="openNewWindow()">Open New Window</button>
</body>
</html>
(b) Write a javascript to create option list containing list of images and then display images in new
window as per selection.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Selector</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
select {
padding: 10px;
font-size: 16px;
}
button {
padding: 10px 15px;
margin: 10px;
cursor: pointer;
background-color: #007BFF;
color: white;
border: none;
border-radius: 5px;
}
button:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<h1>Select an Image</h1>
<select id="imageSelector">
<option value="">Select an image</option>
<option value="https://via.placeholder.com/600x400.png?text=Image+1">Image 1</option>
<option value="https://via.placeholder.com/600x400.png?text=Image+2">Image 2</option>
<option value="https://via.placeholder.com/600x400.png?text=Image+3">Image 3</option>
<option value="https://via.placeholder.com/600x400.png?text=Image+4">Image 4</option>
<option value="https://via.placeholder.com/600x400.png?text=Image+5">Image 5</option>
<option value="https://via.placeholder.com/600x400.png?text=Image+6">Image 6</option>
</select>
<button onclick="displayImage()">Display Image</button>
<script>
function displayImage() {
const selector = document.getElementById("imageSelector");
const selectedImageUrl = selector.value; // Get the selected image URL
if (selectedImageUrl) {
// Open the selected image in a new window
window.open(selectedImageUrl, '_blank');
} else {
alert("Please select an image to display.");
}
}
</script>
</body>
</html>
(c) Write a javascript function to generate Fibonacci series till user defined limit.
Ans.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fibonacci Series Generator</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
button {
padding: 10px 15px;
cursor: pointer;
background-color: #007BFF;
color: white;
border: none;
border-radius: 5px;
}
button:hover {
background-color: #0056b3;
}
.result {
margin-top: 20px;
font-size: 16px;
}
</style>
</head>
<body>
<script>
function generateFibonacci() {
const limit = parseInt(prompt("Enter the limit for Fibonacci series:"), 10); // Get user-defined limit
const resultDiv = document.getElementById("result");
</body>
</html>