0% found this document useful (0 votes)
61 views15 pages

JavaScript Image Rollover Techniques

This document discusses creating image rollovers and more advanced rollover effects using JavaScript. It covers: - Creating basic image rollovers by changing the image source on mouseover and mouseout events. - Improving rollovers by preloading images to avoid loading delays and ensuring images have identical dimensions. - Creating three-state rollovers that change the image based on normal, hover, and active/click states. - Making rollovers accessible by adding alternative text and ensuring they are keyboard navigable. - Implementing "disjointed rollovers" where hovering/clicking one element triggers changes in unrelated elements using event listeners and JavaScript code.

Uploaded by

balrajed082
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views15 pages

JavaScript Image Rollover Techniques

This document discusses creating image rollovers and more advanced rollover effects using JavaScript. It covers: - Creating basic image rollovers by changing the image source on mouseover and mouseout events. - Improving rollovers by preloading images to avoid loading delays and ensuring images have identical dimensions. - Creating three-state rollovers that change the image based on normal, hover, and active/click states. - Making rollovers accessible by adding alternative text and ensuring they are keyboard navigable. - Implementing "disjointed rollovers" where hovering/clicking one element triggers changes in unrelated elements using event listeners and JavaScript code.

Uploaded by

balrajed082
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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="[Link]" id="rollout" alt="" /></a>

<script>
rollout=new Image();
[Link]="[Link]";
rollover=new Image();
[Link]="[Link]";

function onMouseOut(){
[Link]["rollout"].src="[Link]";
};
function onMouseOver(){
[Link]["rollout"].src="[Link]";
};
</script>
</BODY>

NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 1


[Link]
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


[Link]
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


[Link]
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(){
[Link]("disp").innerHTML= " Active Mode";

NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 4


[Link]
JavaScript UNIT III

}
function normal(){
[Link]("disp").innerHTML= " Normal Mode";
}
function hower(){
[Link]("disp").innerHTML= " Hower Mode";
}
</script>
</center>
</body>
</html>

NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 5


[Link]
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


[Link]
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


[Link]
JavaScript UNIT III

</a>
<span class="target">Target</span>
<script>
// JavaScript for disjointed rollovers
const button = [Link]('.button');
const target = [Link]('.target');

[Link]('mouseover', function() {
[Link] = '#f39c12';
[Link] = '#ffffff';
});

[Link]('mouseout', function() {
[Link] = '#eeeeee';
[Link] = '#333333';
});
</script>
</center>
</body>
</html>

NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 8


[Link]
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


[Link]
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


[Link]
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="[Link]" style="width:100%">
<div class="text">Caption Text</div>
</div>

<div class="mySlides fade">


<div class="numbertext">2 / 3</div>
<img src="[Link]" style="width:100%">
<div class="text">Caption Two</div>
</div>

<div class="mySlides fade">


<div class="numbertext">3 / 3</div>
<img src="[Link]" 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


[Link]
JavaScript UNIT III

showSlides(slideIndex);

function plusSlides(n) {
showSlides(slideIndex += n);
}

function currentSlide(n) {
showSlides(slideIndex = n);
}

function showSlides(n) {
let i;
let slides = [Link]("mySlides");
let dots = [Link]("dot");
if (n > [Link]) {slideIndex = 1}
if (n < 1) {slideIndex = [Link]}
for (i = 0; i < [Link]; i++) {
slides[i].[Link] = "none";
}
for (i = 0; i < [Link]; i++) {
dots[i].className = dots[i].[Link](" active", "");
}
slides[slideIndex-1].[Link] = "block";
dots[slideIndex-1].className += " active";
}
</script>
</body>
</html>

NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 12


[Link]
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 = [Link]("mySlides");
let dots = [Link]("dot");
for (i = 0; i < [Link]; i++) {
slides[i].[Link] = "none";
}
slideIndex++;
if (slideIndex > [Link]) {slideIndex = 1}
for (i = 0; i < [Link]; i++) {
dots[i].className = dots[i].[Link](" active", "");
}
slides[slideIndex-1].[Link] = "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([Link]()*[Link]) method. It will generate a random

NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 13


[Link]
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">
[Link]("showImage").onclick = showImage;

function showImage() {
var images = [
{link: "[Link]", width: "300",
height: "200"},
{link: "[Link]",width: "300",
height: "200"},
{link: "[Link]",
width: "300",
height: "200"}
];

var random = [Link]([Link]() * [Link]);

NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 14


[Link]
JavaScript UNIT III

var image = [Link]("img");


[Link] = images[random].link;
[Link] = images[random].width;
[Link] = images[random].height;

var elImgs = [Link]("img");

if ([Link] > 0) {
[Link](image, elImgs[0]);
} else {
[Link](image);
}
}
</script>
</center>
</body>
</html>

NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 15


[Link]

Common questions

Powered by AI

JavaScript rollovers enhance a website's interactivity and visual appeal by providing immediate visual feedback in response to user actions, such as hovering or clicking. This can guide user navigation by visually differentiating interactive elements and making the interface intuitive. In modern web design, rollovers can be used to control media elements, reveal additional content, or animate UI elements, aiding usability and engagement by making interfaces more dynamic and responsive to user input. They increase user satisfaction by providing smoother, more engaging interactions, thereby improving the overall experience .

Disjoint rollovers coordinate interaction effects between unrelated HTML elements by using JavaScript event listeners to manage the state changes independently of the elements' structural hierarchy. Through event listeners such as mouseover, mouseout, or click, actions on one element, like a button, can trigger visual or content changes in a separate element, like altering the style of a distant div. This is achieved by manipulating the Document Object Model (DOM) without a direct parent-child relationship, allowing diverse interface interactions without altering the underlying HTML structure .

To ensure JavaScript rollover effects are accessible and comply with Section 508, developers should guarantee keyboard accessibility by allowing keyboard navigation and operation for all interactive elements. This involves using clear visual indicators for focus states, providing alternative text for rollover images for screen readers, and ensuring all interactions are operable with the keyboard. Testing with assistive technologies is crucial to verify accessibility. Additionally, developers should follow the principles of graceful degradation, ensuring that essential functionalities remain accessible when JavaScript is disabled .

Preloading images is essential in JavaScript rollovers to ensure that the replacement image appears immediately without delay, enhancing the illusion of animation. By storing images in variables and preloading them into the browser's cache, it minimizes fetching time from the server. This is achieved by assigning images to variables in JavaScript so they are cached on the user's hard drive. Efficient techniques include ensuring identical dimensions between original and replacement images to avoid unwanted resizing and using CSS for styling to separate behavior logic from presentation. Preloading also reduces server load and improves overall performance of web interactions .

Creating a basic image rollover involves changing image sources within the same element using onmouseover and onmouseout events, which is relatively straightforward as it deals with changing the attribute of a single element. The challenges here include ensuring images are preloaded for instantaneous effect and managing size consistency. In contrast, disjointed rollovers add complexity by affecting separate, unrelated elements using JavaScript events. They require precise event handling logic and efficient DOM manipulation to manage changes across multiple elements. This involves understanding and coordinating event listeners to trigger appropriate visual changes, which can introduce synchronization challenges .

Improving DOM manipulation performance in JavaScript involves minimizing direct modifications of the DOM. Using document fragments for batch operations and making changes to CSS classes rather than styles directly helps optimize performance. Efficient use of event delegation and controlling the reflow and repaint by minimizing style changes during critical user interactions are important. Applying styles declaratively through CSS and handling simple visual interactions with it, instead of dynamic JavaScript, reduce performance overhead. Also, reducing the number of DOM elements being updated simultaneously enhances rendering speed .

Rollover images must have identical dimensions to prevent browsers from resizing them during the rollover effect, which could result in distortion. Mismatched image sizes lead to visible resizing artifacts, disrupting the rollover effect's smoothness and potentially jarring the user with unexpected layout shifts. Consistent sizing ensures that the transition between images appears seamless, maintaining the intended visual experience without unintended visual or performance issues .

JavaScript slideshows use event handling to cycle through images by attaching event listeners to navigation elements such as next and previous buttons or via automated timing functions to trigger image changes. Considerations for maintaining performance efficiency include preloading images to reduce load time, minimizing DOM manipulation by reusing nodes, and implementing debouncing functions to manage rapid interactions effectively. Optimizing the responsiveness of event listeners and avoiding blocking the UI thread with heavy operations ensure a smooth user experience .

Designing with CSS and JavaScript separately improves maintainability by adhering to the principle of separation of concerns, where CSS manages presentation and layout, while JavaScript handles behavior. This modular approach allows developers to update visual styles without altering logic, facilitating easier maintenance and team collaboration. It also enhances versatility as styling changes can be made for various devices or conditions (responsive design) independent from interactive logic, enabling more scalable and adaptive web application designs .

Three-state rollovers add an extra dimension to the basic two-image rollovers by incorporating a third image that appears when an element, such as a button, is active. This allows for a more interactive and visual feedback system to the user, indicating different states like normal, hover, and active. The benefits include providing a richer user experience, clearer navigation cues, and more effective visual communication, especially for interactive components that require clear feedback for actions such as clicks .

You might also like