Javascript rollovers

Introduction

In this tutorial, we will look at different ways to add javascript rollovers effects to HTML elements on a web page

Standard Javascript rollovers

On many web pages, javascript rollovers are handled by adding an onmouseover and onmouseout event on images.

  • onmouseover is triggered when the mouse moves over an element
  • onmouseout is triggered when the mouse moves away from the element

This is an example of how it works. Move your mouse over the arrow below:

This is the code used:

<img src="images/arrow.gif" onmouseover="this.src='images/arrow-over.gif'" onmouseout="this.src='images/arrow.gif'">

When the mouse moves over the images, the source of the image is set to arrow-over.gif(the green arrow). When the mouse moves away from the image, the source is reverted to the blue arrow(arrow.gif).

CSS rollovers with Javascript

Instead of changing the src attribute of an image, you can also use Javascript to change the css class of an element.

This is an example:

Move your mouse over me

This is the code used:

<style type="text/css">
.arrowOver{
   background-repeat:no-repeat;
   background-image:url('images/arrow-over.gif');
   color:blue; }
</style>
<p onmouseover="this.className='arrowOver'" onmouseout="this.className=''">Move your mouse over me</p>

When you move the mouse over the text, it will assign the element to the css class "arrowOver". This will apply all the layout defined in the <style> part above to this element, i.e. a background image and blue text. This styling will be removed when the mouse moves away from the text.

CSS styling with mootools

Mootools is one of many great libraries which makes it easier to work with Javascript. This is an example of how you can use mootools to add Javascript rollover effects:

Move your mouse over me

This is the code used for this example:

<style type="text/css">
.arrowOver, .standardArrow{
   background-repeat:no-repeat;
}
p.arrowOver{
   background-image:url('images/arrow-over.gif');
   color:green;
}
.standardArrow{
   background-image:url('images/arrow.gif');
   color:blue;
}
</style>
<p class="standardArrow" onmouseover="$(this).addClass('arrowOver')" onmouseout="$(this).removeClass('arrowOver')">Move your mouse over me</p>

In this example, we are using two css classes, standardArrow and arrowOver.

An element on a web page can be assigned to more than one css class. In these cases, the styling you end up with will be a mix of these css classes. In the <style> part above, I have added a p. in front of arrowOver in order to give it precedence over standardArrow

When the mouse moves over the element, the css class arrowOver will be added to the element. When the mouse moves away from the element, it will be removed.

Automate it with Mootools

It always feels better to work with small and clean files instead of a large file containing a mix of HTML, Javascript and CSS. This is one of the reason why it's a good idea to have HTML, Javascript and CSS in separate files. It gives you more freedom and it also makes it much easier for you to maintain your site.

This is something we can accomplish by adding events dynamically, using plain Javascript or with a library like mootools.

Here, I want to show you how this can be done using Mootools.

Demo example - Move your mouse over the elements below:

Menu item 1

Menu item 2

Menu item 3

Menu item 4

Step 1: Plain HTML

The first thing we do is to write our plain HTML code:

<p class="standardArrow"><a href="#">Menu item 1</a></p>
<p class="standardArrow"><a href="#">Menu item 2</a></p>
<p class="standardArrow"><a href="#">Menu item 3</a></p>
<p class="standardArrow"><a href="#">Menu item 4</a></p>

As you can see, there is no Javascript here. All we have done is to create some <p> tags assigned to the standardArrow css class with some anchor tags inside it.

Step 2: CSS inside separate file

The next thing to do is to create a sub folder called css, and inside it a file called javascript-rollovers.css. This is the content of this file:

.arrowOver, .standardArrow{
   background-repeat:no-repeat;
   margin-bottom:0px;
   margin-top:0px;
}
p.arrowOver{
   background-image:url('../images/arrow-over.gif');
   color:green;
}
.standardArrow{
   background-image:url('../images/arrow.gif');
   color:blue;
}

The css is almost identical to the one used in the previous example. We have only added a ../ prefix to the urls in order to have a relative paths from the css file.

Then we include this css file our web page using the <link> tag:

<link rel="stylesheet" href="css/javascript-rollovers.css">

Step 3: Javascript in separate file

We also create a sub folder called js which would be the folder for our Javascript code. Inside it, we create a new file called javascript-rollovers.js. This is the content of this file:

window.addEvent('domready', function() {
   var els = $$('.standardArrow');
   // Getting size of array as a variable for Javascript speed purpose
   var countEls = els.length;
   for(i=0;i<countEls;i++) {
     els[i].addEvent('mouseover', arrowMouseover);
     els[i].addEvent('mouseout', arrowMouseout);
   }
});

function arrowMouseover(){
   $(this).addClass('arrowOver');
}
function arrowMouseout(){
   $(this).removeClass('arrowOver');
}

The first thing we do in this code is to add a domready event. This event will be triggered when the HTML or Document Object Model(DOM) of our web page has been loaded by the browser. When this happens, the function assigned to the event will be executed.

Inside this function, I'm creating an array of all elements on my page assigned to the css class standardArrow

var els = $$('.standardArrow');

The I loop through each of these elements and assign an onmouseover and onmouseout event to each of them.

els[i].addEvent('mouseover', arrowMouseover);
els[i].addEvent('mouseout', arrowMouseout);

When the mouse moves over the element, it will call the function named arrowMouseover and when the mouse moves away from it, it will call the function arrowMouseout.

These two function both consists of only one line. It simply adds and removes the arrowOver css class from the element triggering the event.

function arrowMouseover(){
   $(this).addClass('arrowOver');
}
function arrowMouseout(){
   $(this).removeClass('arrowOver');
}

The last thing we have to do is to include javascript-rollovers.js on our web page using the <script> tag:

<script type="text/javascript" src="js/javascript-rollovers.js"></script>

 

Comments

JamieSware
Vexing https://greenrevolution.com/products/edibles/doozies/ quest of the sooner metre was an eye-opening experience. The diminution and euphoria were unexpected but welcomed. It enhanced my sensory intuition and sparked a newfound increase in support of music and art. Setting aside how, the intense starvation caught me off guard. Inclusive, it was a illustrious introduction to a late life of sensations.
JamieSware at 03:27AM, 2024/06/15.
TerryAccom
Disquieting [url=https://www.nothingbuthemp.net/collections/cbd-tea ]cbd tea bags[/url] has been quite the journey. As someone fervent on usual remedies, delving into the to the max of hemp has been eye-opening. From THC tinctures to hemp seeds and protein puissance, I've explored a brand of goods. Regard for the misunderstanding surrounding hemp, researching and consulting experts tease helped navigate this burgeoning field. Overall, my sophistication with hemp has been despotic, contribution holistic well-being solutions and sustainable choices.
TerryAccom at 02:39PM, 2024/07/10.
MichaelPrice
I've been using [url=https://greenrevolutioncbd.com/product/cbd-cbg-gummies/ ]cbg and cbd gummies[/url] with a view across two years now, and the experience has been transformative. CBD unguent has markedly improved my slumber quality and reduced my anxiety levels. The edibles are a advantageous and enjoyable passage to merge CBD into my commonplace routine. I rate the spontaneous propositions to wellness that CBD offers, and I've capable no adverse side effects. Importantly recommend in behalf of those seeking a simpleton selection to traditional medications.
MichaelPrice at 05:29PM, 2024/07/18.
EloiseSnive
I've been using CBD gummies for or a year conditions, and I can't have the courage of one's convictions pretend how much they've improved my preoccupation like [url=https://www.cornbreadhemp.com/products/full-spectrum-cbd-gummies ]cbd/thc gummies[/url] ! The flavors are at rest delicious, making it a attractive part of my commonplace routine. My anxiety and bring home levels have significantly decreased, and my beauty sleep calibre has improved tremendously. I wake up premonition more refreshed and energetic. Be that as it may, I've noticed a jot of drowsiness during the lifetime, and I care the effects lasted a whit longer. In spite of these minor issues, I highly commend these CBD gummies after anyone looking to enhance their well-being instinctively!
EloiseSnive at 03:19PM, 2024/07/21.
HaroldRhype
Exploring https://rvfhemp.com/pages/where-to-order-hemp-flower-in-florida and pre roll weed has been an enlightening passing as me. The je sais quoi and smell of these products are provocative, gift a calming and enjoyable experience. Whether I'm unwinding after a covet day or seeking resourceful ardour, hemp pre-rolls produce a understandable additional that I can trust. The convenience of pre-rolls combined with the benefits of hemp flowers secure them a go-to choice for the purpose slackening and mindfulness. I appreciate the limelight to squad and purity of the products, enhancing my comprehensive satisfaction. Exceptionally recommend troublesome hemp flowers and pre-rolls in place of a holistic and fulfilling experience!
HaroldRhype at 02:47PM, 2024/08/08.
RichardDus
Fatiguing https://www.nothingbuthemp.net/products/indica-gummies has been perfectly the journey. As someone pointed on spontaneous remedies, delving into the world of hemp has been eye-opening. From THC tinctures to hemp seeds and protein puissance, I've explored a type of goods. Regard for the misunderstanding surrounding hemp, researching and consulting experts tease helped cross this burgeoning field. Overall, my undergo with hemp has been despotic, sacrifice holistic well-being solutions and sustainable choices.
RichardDus at 10:16PM, 2024/09/12.
RichardDus
Disquieting https://www.nothingbuthemp.net/collections/thc-gummies-for-sex has been perfectly the journey. As someone rapier-like on unpretentious remedies, delving into the coterie of hemp has been eye-opening. From THC tinctures to hemp seeds and protein pulverize, I've explored a brand of goods. Despite the confusion surrounding hemp, researching and consulting experts have helped cross this burgeoning field. Entire, my experience with hemp has been positive, sacrifice holistic well-being solutions and sustainable choices.
RichardDus at 05:08PM, 2024/09/13.
Jeffreygox
I recently cast-off this purlieus to lay one's hands on https://synergy3.com/hvac/heating/repair-maintenance/ , and I couldn’t be happier with the results. The search was straightforward, and I appreciated the particularized profiles and buyer reviews for each contractor. It мейд comparing options and reading round other clients' experiences easy. The contractors I contacted were prompt, efficient, and offered competitive quotes. This locality is a spectacular resource seeing that anyone needing trusty home repair services. Greatly recommended as a replacement for its simple interface and eminence listings!
Jeffreygox at 08:54PM, 2024/09/18.
Shaungaw
I recently tried the [url=https://www.leoweekly.com/cannabis/best-chill-gummies-rating-2024-16884743]best chill gummies[/url] and they are awesome! The flavor is considerable and they victual a nice, relaxing effect without being too overpowering. Faultless pro unwinding after a extensive day. They helped me manipulate placidity and focused, and I be fond of that they’re made with unembellished ingredients. The packaging is convenient too, making it unoppressive to take them on the go. All-inclusive, I’m really impressed and when one pleases finally be buying more!
Shaungaw at 06:27PM, 2024/09/27.
Trentinowl
Exploring [url=https://rvfhemp.com/collections/pre-rolls ]cbd pre roll[/url] and pre roll weed has been an enlightening journey as me. The quality and aroma of these products are exciting, sacrifice a calming and enjoyable experience. Whether I'm unwinding after a crave period or seeking original incentive, hemp pre-rolls produce a understandable choice that I can trust. The convenience of pre-rolls combined with the benefits of hemp flowers occasion them a go-to voice instead of off and mindfulness. I perceive the attention to group specifically and harmlessness of the products, enhancing my all-inclusive satisfaction. Greatly recommend troublesome hemp flowers and pre-rolls to a holistic and fulfilling trial!
Trentinowl at 07:44PM, 2024/10/21.
AnthonyFab
I recently used this purlieus to allot https://synergy3.com/hvac/heating/ , and I couldn’t be happier with the results. The search was straightforward, and I appreciated the detailed profiles and customer reviews for each contractor. It made comparing options and reading about other clients' experiences easy. The contractors I contacted were prompt, licensed, and offered competitive quotes. This milieu is a unbelievable resource for anyone needing safe home vamp services. Warmly recommended as a replacement for its explicit interface and eminence listings!
AnthonyFab at 04:14PM, 2024/11/06.
Brucenog
Exploring [url=https://rvfhemp.com/products/florida-berry-flower ]blueberry cbd flower[/url] and pre roll weed has been an enlightening voyage as me. The je sais quoi and smell of these products are provocative, sacrifice a calming and enjoyable experience. Whether I'm unwinding after a extensive date or seeking original enthusiasm, hemp pre-rolls plan for a common choice that I can trust. The convenience of pre-rolls combined with the benefits of hemp flowers make them a go-to select instead of relaxation and mindfulness. I appreciate the r‚clame to squad and purity of the products, enhancing my overall satisfaction. Decidedly recommend troublesome hemp flowers and pre-rolls in place of a holistic and fulfilling trial!
Brucenog at 07:41PM, 2024/11/06.
Eugeneclalm
Exploring https://rvfhemp.com/products/sativa-gummies and pre roll weed has been an enlightening voyage as me. The je sais quoi and aroma of these products are exciting, offering a calming and enjoyable experience. Whether I'm unwinding after a covet light of day or seeking originative enthusiasm, hemp pre-rolls provide a understandable additional that I can trust. The convenience of pre-rolls combined with the benefits of hemp flowers occasion them a go-to voice instead of r 'rest and mindfulness. I treasure the r‚clame to squad and purity of the products, enhancing my all-inclusive satisfaction. Decidedly advocate stressful hemp flowers and pre-rolls to a holistic and fulfilling event!
Eugeneclalm at 02:19PM, 2024/11/18.
WalterKip
Worrisome <a href=https://www.nothingbuthemp.net/pages/buy-delta-9-thc-online-in-florida>online dispensary that ships to florida</a> has been somewhat the journey. As someone keen on spontaneous remedies, delving into the coterie of hemp has been eye-opening. From THC tinctures to hemp seeds and protein competency, I've explored a miscellany of goods. Despite the confusion neighbourhood hemp, researching and consulting experts own helped pilot this burgeoning field. Inclusive, my sophistication with hemp has been optimistic, contribution holistic well-being solutions and sustainable choices.
WalterKip at 01:25AM, 2024/11/19.
Eugeneclalm
Exploring https://rvfhemp.com/products/strawberry-sunshine-flower and pre roll weed has been an enlightening trip for me. The worth and aroma of these products are stirring, offering a calming and enjoyable experience. Whether I'm unwinding after a crave date or seeking creative ardour, hemp pre-rolls provide a natural alternative that I can trust. The convenience of pre-rolls combined with the benefits of hemp flowers make them a go-to fitting instead of off and mindfulness. I appreciate the r‚clame to group specifically and honesty of the products, enhancing my all-inclusive satisfaction. Greatly praise tough hemp flowers and pre-rolls for a holistic and fulfilling sagacity!
Eugeneclalm at 01:39PM, 2024/11/19.

Post your comment

Don't have an avatar? Create one at Gravatar.com.

Confirmation code:


About/Contact | A good idea? | Submit a script | Privacy notice
© 2005 - 2010 dhtmlgoodies.com | post@dhtmlgoodies.com