JavaScript UNIT III
UNIT – II
Creating Rollovers and More
3.1 Creating Basic Image Rollover
JavaScript is the most popular lightweight scripting language. It is easy to use to build a
dynamic and interactive website. One of its useful functionalities is image rollover that is
changing an image into another image when a mouse hovers over the original image. Then the
new image will change back to the original one when the mouse moves away.
An image rollover is basically two different images. One is displayed after the page loaded up,
the other one is displayed only when the user moves his mouse over the first one. Image
rollovers are often used for a site’s interface.
onmouseover : is triggered when the mouse moves over an element
onmouseout : is triggered when the mouse moves away from the element
Example:
<html>
<head>
<BODY>
<a href="" onmouseover="onMouseOver()" onmouseout="onMouseOut()">
<img src="out.gif" id="rollout" alt="" /></a>
<script>
rollout=new Image();
rollout.src="out.gif";
rollover=new Image();
rollover.src="over.gif";
function onMouseOut(){
document.images["rollout"].src="out.gif";
};
function onMouseOver(){
document.images["rollout"].src="over.gif";
};
</script>
</BODY>
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 1
www.nandigramiit.org
JavaScript UNIT III
</head>
</html>
Two images are loaded into web browser cache by a JavaScript code. One of the two
preloaded images is placed in the web document by <img> HTML tag.
When mouse pointer is moved over the image, the other preloaded one is displayed.
When mouse pointer is moved out from the image, the initial one is displayed.
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 2
www.nandigramiit.org
JavaScript UNIT III
3.2 How to Create Better Rollover
To make the illusion of animation work, you need to make sure that the replacement image
appears immediately, with no delay while it is fetched from the server. To do that, you use
JavaScript to place the images into variables used by your script, which preloads all the images
into the browser’s cache (so that they are already on the user’s hard disk when they are needed).
Then, when the user moves the mouse over an image, the script swaps out one variable
containing an image for a second variable containing the replacement image
1. When you prepare your graphics for rollovers, make sure that all your GIF or PNG
images are not transparent. If they are, you will see the image you are trying to replace
beneath the transparent image—and that’s not what you want.
2. Both the original and the replacement images need to have identical dimensions.
Otherwise, some browsers resize the images for you, and you probably won’t like the
distorted result.
3. Use CSS for Basic Styling: Rollover effects usually involve changing the appearance
of an element when the user hovers over it. For simple changes like color, size, or
opacity, it's often more efficient to use CSS :hover pseudo-class.
4. Separation of Concerns: Keep your JavaScript focused on behavior rather than
presentation. Use JavaScript to handle interactions and logic, while CSS handles the
styling.
5. Event Handling: Use event listeners to detect when the mouse enters and leaves the
element. In JavaScript, you can use mouseover and mouseout events, or mouseenter
and mouseleave for more precise control.
6. Efficient DOM Manipulation: If you're dynamically changing styles or content,
consider performance implications, especially if you're targeting multiple elements.
Batch DOM manipulations when possible.
7. Accessibility: Ensure that your rollover effects are accessible to all users, including
those who navigate via keyboard or assistive technologies. Test with screen readers and
keyboard navigation to ensure a smooth experience.
8. Graceful Degradation: If JavaScript is disabled or not supported, make sure the
essential functionality is still accessible. Use progressive enhancement techniques to
enhance the experience for users with JavaScript enabled.
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 3
www.nandigramiit.org
JavaScript UNIT III
3.3 Creating Three State Rollover:
A three-state rollover is one where the rollover has three versions. Besides the original image
and the version that appears when the user places the cursor over the image, there is a third
version of the image when the button itself is clicked.
Creating three-state rollovers in JavaScript involves changing the appearance of an element
when it is in different states (usually normal, hover, and active). Here's a basic example of how
you can achieve this:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Three-State Rollovers</title>
<style>
/* Define styles for normal, hover, and active states */
.button {
display: inline-block;
padding: 10px 20px;
background-color: #3498db; /* Normal state color */
color: #ffffff;
text-decoration: none;
border-radius: 5px;
}
.button:hover {
background-color: #83922e; /* Hover state color */
}
.button:active {
background-color: #a56410; /* Active state color */
}
</style>
</head>
<body>
<center>
<!-- HTML element with three-state rollovers -->
<h2 style="color:green">Three-State Rollovers</h2>
<a href="#" class="button" onclick="active()"
onmouseout="normal()"onmouseover="hower()">TSR</a> </br> </br>
<div id="disp" style="color:green; font-size:18px;"> </div>
<script>
function active(){
document.getElementById("disp").innerHTML= " Active Mode";
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 4
www.nandigramiit.org
JavaScript UNIT III
}
function normal(){
document.getElementById("disp").innerHTML= " Normal Mode";
}
function hower(){
document.getElementById("disp").innerHTML= " Hower Mode";
}
</script>
</center>
</body>
</html>
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 5
www.nandigramiit.org
JavaScript UNIT III
3.4 Making Rollover Accessible and 508 Compliant:
To make rollovers accessible and compliant with Section 508 (and other accessibility
guidelines), you should ensure that they are keyboard accessible, provide clear visual
indicators, and have alternative text for screen readers.
3.5 making disjointed rollovers in:
Disjointed rollovers involve creating rollover effects where the hover or active state of one
element triggers changes in another element.
In JavaScript, "disjoint rollovers" typically refer to rollover effects where the hover or active
state of one element triggers changes in another unrelated element on the page. These effects
are disjointed because the interaction between the elements is not directly connected through
their HTML structure but rather through event listeners and JavaScript code.
For example, in a disjoint rollover scenario:
Hovering over a button might change the color of a separate div elsewhere on the page.
Moving the mouse over an image could trigger the display of additional information in
a different section of the page.
Clicking on a menu item could cause a completely different element, like a modal or a
sidebar, to open or close.
These disjointed rollover effects can be achieved using JavaScript event listeners such as
mouseover, mouseout, mouseenter, mouseleave, click, etc., to detect
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 6
www.nandigramiit.org
JavaScript UNIT III
interactions with one element and then apply changes to another element based on those
interactions.
The key aspect of disjoint rollovers is that the elements involved might not have a direct
parent-child relationship or any inherent connection in the HTML structure, but their
behaviours are coordinated through JavaScript.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Disjointed Rollovers</title>
<style>
/* Define styles for normal and hover states */
.button {
display: inline-block;
padding: 10px 20px;
background-color: #3498db; /* Normal state color */
color: #ffffff;
text-decoration: none;
border-radius: 5px;
cursor: pointer; /* Change cursor to pointer for better usability */
margin-right: 10px;
}
.target {
display: inline-block;
padding: 10px 20px;
background-color: #eeeeee; /* Normal state color */
color: #333333;
border-radius: 5px;
margin-left: 10px;
}
.button:hover,
.button:focus {
background-color: #2980b9; /* Hover state color */
}
</style>
</head>
<body>
<center>
<!-- HTML elements for disjointed rollovers -->
<h2 style="color:green">Disjointed Rollovers</h2>
<a href="#" class="button" role="button">
Button
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 7
www.nandigramiit.org
JavaScript UNIT III
</a>
<span class="target">Target</span>
<script>
// JavaScript for disjointed rollovers
const button = document.querySelector('.button');
const target = document.querySelector('.target');
button.addEventListener('mouseover', function() {
target.style.backgroundColor = '#f39c12';
target.style.color = '#ffffff';
});
button.addEventListener('mouseout', function() {
target.style.backgroundColor = '#eeeeee';
target.style.color = '#333333';
});
</script>
</center>
</body>
</html>
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 8
www.nandigramiit.org
JavaScript UNIT III
3.6 Creating Slideshows:
Slideshow is nothing but showing images one after another after specific duration say 1 second.
You might have already seen your photos in your computer in a slideshow. Correct! This is the
same. We are going to implement slideshow using HTML, CSS and JavaScript.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {box-sizing: border-box}
body {font-family: Verdana, sans-serif; margin:0}
.mySlides {display: none}
img {vertical-align: middle;}
/* Slideshow container */
.slideshow-container {
max-width: 1000px;
position: relative;
margin: auto;
}
/* Next & previous buttons */
.prev, .next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
padding: 16px;
margin-top: -22px;
color: white;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
user-select: none;
}
/* Position the "next button" to the right */
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 9
www.nandigramiit.org
JavaScript UNIT III
/* On hover, add a black background color with a little bit see-through */
.prev:hover, .next:hover {
background-color: rgba(0,0,0,0.8);
}
/* Caption text */
.text {
color: #f2f2f2;
font-size: 15px;
padding: 8px 12px;
position: absolute;
bottom: 8px;
width: 100%;
text-align: center;
}
/* Number text (1/3 etc) */
.numbertext {
color: #f2f2f2;
font-size: 12px;
padding: 8px 12px;
position: absolute;
top: 0;
}
/* The dots/bullets/indicators */
.dot {
cursor: pointer;
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.active, .dot:hover {
background-color: #717171;
}
/* Fading animation */
.fade {
animation-name: fade;
animation-duration: 1.5s;
}
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 10
www.nandigramiit.org
JavaScript UNIT III
@keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
/* On smaller screens, decrease text size */
@media only screen and (max-width: 300px) {
.prev, .next,.text {font-size: 11px}
}
</style>
</head>
<body>
<div class="slideshow-container">
<div class="mySlides fade">
<div class="numbertext">1 / 3</div>
<img src="img1.jpg" style="width:100%">
<div class="text">Caption Text</div>
</div>
<div class="mySlides fade">
<div class="numbertext">2 / 3</div>
<img src="img2.jpg" style="width:100%">
<div class="text">Caption Two</div>
</div>
<div class="mySlides fade">
<div class="numbertext">3 / 3</div>
<img src="img3.jpg" style="width:100%">
<div class="text">Caption Three</div>
</div>
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
</div>
<br>
<div style="text-align:center">
<span class="dot" onclick="currentSlide(1)"></span>
<span class="dot" onclick="currentSlide(2)"></span>
<span class="dot" onclick="currentSlide(3)"></span>
</div>
<script>
let slideIndex = 1;
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 11
www.nandigramiit.org
JavaScript UNIT III
showSlides(slideIndex);
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
let i;
let slides = document.getElementsByClassName("mySlides");
let dots = document.getElementsByClassName("dot");
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " active";
}
</script>
</body>
</html>
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 12
www.nandigramiit.org
JavaScript UNIT III
Automatic Slideshow: replace JavaScript code from above example and add following
JavaScript code.
<script>
let slideIndex = 0;
showSlides();
function showSlides() {
let i;
let slides = document.getElementsByClassName("mySlides");
let dots = document.getElementsByClassName("dot");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndex++;
if (slideIndex > slides.length) {slideIndex = 1}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " active";
setTimeout(showSlides, 2000); // Change image every 2 seconds
}
</script>
3.7 Displaying Random Images:
The random image generator concept is mostly used for advertisement. The images you see on
a website generating randomly, are already stored in a database or an array. These images
display to the user within a regular time interval or change by a click. You can also provide the
address of an image directly from the internet.
Steps for Random Image Generator
Declare an array using JavaScript to store the images.
Provide the link or URL of images in the declared array. You can also pass the height
and width in the array for the image size to display on the webpage.
Declare a JavaScript variable to store a random value calculated using
this floor(Math.random()*randomImage.length) method. It will generate a random
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 13
www.nandigramiit.org
JavaScript UNIT III
number between 0 and the length of the array that will be assigned to the images to
display randomly.
Now, return the random images selected using a number calculated in the previous step.
Put all the above steps in a user-defined function (getRandomImage), which will call
by clicking on a Generate Image
In HTML code, we will use a tab and provide an ID to display an image over another
image. So, the images will show you one by one, by overwrapping each other.
Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body >
<center>
<h1 style="color:green">NIIT Nanded</h1>
<h3 style="color:rgb(24, 150, 182)">Show Random Image</h3>
<p> A random image is generateed by clicking on a button.</p>
<input type="button" id="showImage" value="Show Image"/>
<style>
img {
display: block;
margin-top: 40px;
margin-left: 300px;
}
</style>
<script type="text/javascript">
document.getElementById("showImage").onclick = showImage;
function showImage() {
var images = [
{link: "img1.jpg", width: "300",
height: "200"},
{link: "img2.jpg",width: "300",
height: "200"},
{link: "img3.jpg",
width: "300",
height: "200"}
];
var random = Math.floor(Math.random() * images.length);
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 14
www.nandigramiit.org
JavaScript UNIT III
var image = document.createElement("img");
image.src = images[random].link;
image.width = images[random].width;
image.height = images[random].height;
var elImgs = document.getElementsByTagName("img");
if (elImgs.length > 0) {
document.body.replaceChild(image, elImgs[0]);
} else {
document.body.appendChild(image);
}
}
</script>
</center>
</body>
</html>
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 15
www.nandigramiit.org