Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery set active/hover background images

Tags:

jquery

css

events

I have a list that has 5 items in, the first one (on load) is active (with a class of 'active' added by jQuery). They all have background images associated with them. If I click any of the li's another div updates with relevant content (this is working).

However I'm struggling with the following:

If you click an li, update its background image to be colour (suffix of '-cl.png'). When I hover over another one, update its background image to be colour and keep the clicked one (with a class of 'active') colour too. If an li is not hovered over set the background image to be black and white (suffix of '-bw.png') but keep the active one colour.

Hope I've explained myself clearly. Any ideas on how I can achieve this? Thanks, Brett

Here's my HTML:

<ul class="graduate_tab">
<li class="graduate1"><a href="#grad1"><span class="gradimg1">grad1</span></a></li>
<li class="graduate2"><a href="#grad2"><span class="gradimg2">grad2</span></a></li>
<li class="graduate3"><a href="#grad3"><span class="gradimg3">grad3</span></a></li>
<li class="graduate4"><a href="#grad4"><span class="gradimg4">grad4</span></a></li>
<li class="graduate5"><a href="#grad5"><span class="gradimg5">grad5</span></a></li></ul>
like image 229
Brett Avatar asked Oct 18 '25 19:10

Brett


2 Answers

First, I would do most of the work in CSS, like this:

.graduate1 { background: url(image1-bw.png); }
.graduate1.active, .graduate1:hover { background: url(image1-cl.png); }
.graduate2 { background: url(image2-bw.png); }
.graduate2.active, .graduate2:hover { background: url(image2-cl.png); }
//etc...

Then in jQuery all you need to worry about is the active class, like this:

$('.graduate_tab li').click( function() {
  $(this).addClass('active').siblings().removeClass('active');
});

Using .addClass() on the clicked one and .removeClass() on the rest will move the active class to the clicked one...if you want to be able to remove it from an already active one (toggle it off) you can replace .addClass() with .toggleClass() for that behavior.

like image 73
Nick Craver Avatar answered Oct 20 '25 09:10

Nick Craver


$('.graduate_tab li').hover(
  function() { 
    $(this).css('background-image','your-image-cl.jpg'); 
  }, function() {
    $(this).css('background-image','your-image.jpg'); 
  });

$('.graduate_tab li').click( function() {
  $('.graduate_tab li').removeClass('active');
  $(this).addClass('active');
});

This should do the trick. In case I forgot something, tell me, and I'll edit the code.

like image 35
3rgo Avatar answered Oct 20 '25 10:10

3rgo