jQuery Basics – Simple Image Roll Overs

May 1st, 2011 | by | jquery, php programming, web development

May
01

jQuery - Write Less do More

Basics Series – Image Rollovers ( 1 of ?? )

I’ve been writing for along time, I’ve used many different libraries and even wrote code before libraries became popular. Anyway, after going from to using the Library to jQuery, I’m hooked on it. With ! you can not create non-obtrusive code, everything has to be complicated. With jQuery everything is simple, the API Documents are excellent and it’s basically a write less and do more library.

jQuery

jQuery


Ok, enough about how great this library is, I’ve decided to write a few articles on using jQuery to do basic things every page requires. In this chapter, I will teach you how to make image rollovers very simple by just locating a class and renaming the Image Source to the Hover Source and then Reversing the Process.

Let’s start out with the code and then I’ll try to expain it afterwards.

View Code JAVASCRIPT
/**
 *
 * Basic Image Roll Over 
 *	
 * Copyright (c) 2011 Shawn Crigger (http://s-vizion.com)
 * Licensed under the MIT License (LICENSE.txt). 
 * Created by Shawn Crigger <shawn@s-vizion.com>
 *
 **/
 
  $("img.rollover").hover(function()
    {
      this.src = this.src.replace(".jpg","_ov.jpg");
    },
    function()
    { this.src = this.src.replace("_ov.jpg",".jpg"); }
  );

Now let me try to explain what happens here.

$(“.rollover”) Will Select All Images that Have the Class “rollover”

Next we set a Event Handler for the Hover property of the Element we just Selected and Create 2 Functions for it.

The First Function Replaces the “.jpg” of the Image Source Tag with “_ov.jpg”
The Second Function Reverses the First Function.

Tags: , , , , , , ,

Authored by

I am a CPU Commando, I work hard to destroy the evil Bill Gates plan's for Global Computer Control and follow Linus Torvalds teachings of Open Source OS's and Free Software ( Free as in Speech not Beer ) When I'm not teaching the world to use Linux then I am trying to teach people proper Web Programming and maybe a little Hacking Aside. If you're reading this on Internet Explorer v?? then your CPU will explode in 10 seconds, your wife will leave you, your dogs will die and your pickup truck will run off a Cliff all on your way to pickup your Mama from the Pen.

  • http://leerileydesigns.com/ Lee

    Thank you! I have been searching forever for something simple like this and finally found it! Any suggestions on how to ease the transition??

  • Anonymous

    You could add a fadeOut and a FadeIn before and after changing the source

    Something like below might work, ( this is just off top of my head if it doesn’t work i can make a quick JSFiddle to test it out with )

    $( this ).fadeOut(‘slow’);
    this.src = this.src.replace(“.jpg”,”_ov.jpg”);
    $( this ).fadeIn(‘slow);