2

i'm trying to acchive this:

I have something like:

<ul>
<li><a href="#" class="class-1">Link 1</a></li>
<li><a href="#" class="class-2">Link 2</a></li>
<li><a href="#" class="class-3">Link 3</a></li>
</ul>

<img src="img-desc.jpg" class="class-1" />
<img src="img-desc-1.jpg" class="class-2" />
<img src="img-desc-2.jpg" class="class-3" />

I want that everytime the user pass the mouse over one of the the ul>li the image with the matching class gets a red border. How can I acchieve this??

Thanks so much to everyone, I hope you can help me out with this.

Alberto
  • 313
  • 1
  • 5
  • 17

1 Answers1

5

You could do this:

Example: http://jsfiddle.net/Q7knH/

$('ul > li').hover(function() {
    $('img.' + $(this).children('a').attr('class') ).css('border','2px solid red');
},function() {
    $('img.' + $(this).children('a').attr('class') ).css('border','');
});

or if you're certain that the <li> elements won't have any whitespace around their <a>, you could make it a little shorter:

Example: http://jsfiddle.net/Q7knH/1/

$('ul > li').hover(function() {
    $('img.' + this.firstChild.className ).css('border','2px solid red');
},function() {
    $('img.' + this.firstChild.className ).css('border','');
});

Or if you wanted the hover to take place on the <a>, then do this:

Example: http://jsfiddle.net/Q7knH/3/

$('ul > li > a').hover(function() {
    $('img.' + this.className ).css('border','2px solid red');
},function() {
    $('img.' + this.className ).css('border','');
});
user113716
  • 318,772
  • 63
  • 451
  • 440
  • 3
    Asker might add more functionality in the future by using `$('img.' + this.className).addClass('some_css_class');` Asker could put whatever he wants in `some_css_class` in addition to the red border so to separate functionality and style. – jamesbtate Jan 20 '11 at 20:14
  • 2
    @puddingfox: I agree. Adding a class with `.addClass()` instead of setting styles directly would be preferred. – user113716 Jan 20 '11 at 20:15