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

Nav
Thank you for all your help. You have made learning DHTML much more fun and interesting.

Kind Reagards
Nav
Nav at 02:43PM, 2011/12/05.
Jocular Johnny
I was able to put rollovers in blogger when I had Windows XP Professional. After I had a computer crash Windows Home was installed and I run IE8.

Now I find I can't do rollover in blogger, nor can I preview rollovers in my browser when working with Serif.

I have also noticed that when I republish posts in blogger that have rollovers in them, they now don't work.

This code had always worked.

<a href="IMAGE-DESTINATION-URL"><img src="IMAGE-1-LINK" onmouseover="this.src='IMAGE-2-LINK'" onmouseout="this.src='IMAGE-1-LINK'" /></a>

I know rollovers contain Javascript and when I try and do them in blogger, I get the notification bar that this page has been modified to protect from cross-site scripting.

Can you possibly help - thank you.
Jocular Johnny at 01:34AM, 2012/02/11.
viswarajramji
this website is awesome enough and made me learn much
viswarajramji at 11:24AM, 2014/04/10.
Jack
Awesome, I just used it on my web page, very easy to implement
Jack at 10:41AM, 2017/01/06.
RobertSwaby
photography jobs rochester ny 529

Bowen McCauley Dance's (BMD) programs are in demand! BMD is looking for qualified Teaching Artists to teach its Studio to the Stage after-school programs. Qualified candidates must have at least 3 years of dance teaching and choreography experience, experience working with children, reliable transportation, and pass a VA State background check. Preferred candidates should hold a Bachelor's degree in Dance or have extensive performance experience. Video Production. We report snowfall in liquid-equivalent terms. The actual depth of new snowfall is typically between 5 and 10 times the liquid-equivalent amount, assuming the ground is frozen. Colder, drier snow tends to be on the higher end of that range and warmer, wetter snow on the lower end.
[url=http://pagebin.com/Ej3SEueI]Photography Jobs Las Vegas Nv 704j Pvd[/url]

photography jobs fredericksburg va dept

A study on the KC-390 (earlier named C-390) aircraft was presented at LAAD 2007. The research and development expenses of C-390 were $600m and shared among Embraer and various partners led by the FAB. Most have a bachelor s degree, but there are some cases of private detectives and investigators who learn on the job. However, most states require a license and some experience. South Carolina Photography Occupations.
[url=http://pagebin.com/x3FbPaHN]Photography Jobs Zachary The Label[/url]

photography jobs lincoln ne doppler

Major employers for Fort Lauderdale jobs include Citrix Systems, AutoNation, Spirit Airlines and DHL Express. The healthcare industry is also flourishing in Fort Lauderdale; the city's largest employer is Tenet Healthcare, with over 5,000 employees. Opportunities abound in nearby South Florida cities; try searching for Pompano Beach jobs to see other options. Many universities, community and junior colleges, vocational–technical institutes, and private trade and technical schools offer classes in photography. Basic courses in photography cover equipment, processes, and techniques. Art schools may offer useful training in photographic design and composition. Featured Partners.
[url=http://pagebin.com/fVvq0buC]Photography Jobs Missouri Women's Basketball[/url]

photography jobs for national geographic website

However, I think my advice applies. Not because I somehow magically know what a career in art is like, but because I think it applies to *all* education and careers. Glassdoor lets you search all open Photography Assistant jobs in Bengaluru. There are 53 Photography Assistant job openings in Bengaluru. Search Photography Assistant jobs in Bengaluru with Glassdoor. Get hired. Love your job. Tarzan did it … now so can you. Flying through the trees at up to 25 miles per hour is an exhilarating experience you'll never forget. The fun begins once you arrive at our base camp, located just off the Pigeon Forge Parkway. You’re ushered to the first line via our unique off-road-style transportation. Our professionally trained guides are with you the entire time to deliver an adrenaline rush unlike any other.
[url=http://sampgahytest.soup.io]Photography Jobs Oahu 5 Star[/url]

photography jobs yellowstone itinerary

Summit Sports LLC Keego Harbor, MI. Mom365’s Vision is that “Every Baby Deserves a Beautiful Photo.” As the largest newborn photography company in the U.S, we are dedicated to living this Vision. Listed four days ago 4d ago.
[url=http://pagebin.com/5SxL2zZt]Photography Jobs Kingsport Tn850[/url]

photography jobs rhode island keno

Gina Wilson Green. Family Photo. Send Feedback for this estimated salary. Diaz Photography 227 Cinnamon Dr. Galt, CA 95632 209-744-9859.
[url=http://prevdiaquotest.soup.io]Photography Jobs In California Judicial Council[/url]

photography jobs tampa fl 910s oil filter 2014 fusion replacement

SCC 7S TICKETS ARE NOW ON SALE (27-Sep-2016. BALANCING EOUIPMENT. Indiana Regional Works Councils.
[url=http://pagebin.com/qverQFBx]Photography Jobs Hampton Roads Transit[/url]
RobertSwaby at 12:34AM, 2017/04/29.
Sensei-sanyk
Подними своё настроение! Заходи в нашу группу вконтакте https://vk.com/Vash_Pozitiv, в которой ежечасно публикуются отборные шутки! Отличное настроение гарантируем :-)
Sensei-sanyk at 02:58AM, 2017/04/29.

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