views:

30

answers:

2

Hello everyone,

I'm trying to do a simple task with jQuery: I have a list of words which, when hovered, should fadeIn its corresponding image. For example:

<a href="#" class="yellow">Yellow</a>
<a href="#" class="blue">Blue</a>
<a href="#" class="green">Green</a>

<img src="yellow.jpg" class="yellow">
<img src="blue.jpg" class="blue">
<img src="green.jpg" class="green">

I'm currently doing it this way for each link/image:

$('a.yellow').hover(
  function () {
    $('img.yellow').fadeIn('fast');
    },
    function () {
     $('img.yellow').fadeOut('fast');
     });

The method above works fine, but as I'm still learning, I guess there's a better way to do that instead of repeating functions.

Can anyone give me some light here? How can I improve this code?

+4  A: 
<a href="#" class="yellow" data-type="color">Yellow</a>
<a href="#" class="blue" data-type="color">Blue</a>
<a href="#" class="green" data-type="color">Green</a>

jQuery Code

$('a[data-type=color]').hover(
  function () {
    $('img.'+$(this).attr("class")).fadeIn('fast');
    },
    function () {
     $('img.'+$(this).attr("class")).fadeOut('fast');
     });
});

I think you should try this one. I used data- as prefix for custom defined attributes because it is html5 compliant. You can say data-something if you want to.

Normally you may not need to use data-color custom attribute but since I think to make it more generic, I used that attribute. You can do such code as well :

<a href="#" class="yellow">Yellow</a>
<a href="#" class="blue">Blue</a>
<a href="#" class="green">Green</a>

Then

$('a').hover(
  function () {
    $('img.'+$(this).attr("class")).fadeIn('fast');
    },
    function () {
     $('img.'+$(this).attr("class")).fadeOut('fast');
     });
});

But this way, you should make sure all the links are image related links.

Braveyard
Whoa, thanks a lot! Working fine here.
Vitor
+2  A: 
<a href="#" id="yellow" class="colorLink">Yellow</a>
<a href="#" id="blue" class="colorLink">Blue</a>
<a href="#" id="green" class="colorLink">Green</a>

<img src="yellow.jpg" class="yellow">
<img src="blue.jpg" class="blue">
<img src="green.jpg" class="green">

$("a.colorLink").hover(
    function(){
        $("img."+this.id).fadeIn('fast');
    },
    function(){
        $("img."+this.id).fadeOut('fast');
    }
);

This sets a unique id to each link that corresponds to the image.

inkedmn