Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery add a fade to an .addClass

How do I fade .addClass in and out.

Here is the link -

http://www.bikramyogajoondalup.com.au/about-bikram-yoga/postures-benefits.html

and here is the code -

$(document).ready(function() {
  $('#menu li#Q_01,#menu li#Q_03,#menu li#Q_05,#menu li#Q_07,#menu li#Q_09,#menu li#Q_11,#menu li#Q_13').hover(function() {
    $(this).addClass('pretty-hover');
  }, function() {
    $(this).removeClass('pretty-hover');
  });
});

$(document).ready(function() {
  $('#menu li#Q_02,#menu li#Q_04,#menu li#Q_06,#menu li#Q_08,#menu li#Q_10,#menu li#Q_12').hover(function() {
    $(this).addClass('pretty-hover_01');
  }, function() {
    $(this).removeClass('pretty-hover_01');
  });
});

Thanks

like image 977
Nik Avatar asked Apr 27 '10 06:04

Nik


1 Answers

If jQuery UI is an option, you can use .toggleClass(class, duration) for this.

Also, you can probably simplify your selector, it looks like :even and :odd will do the job based on your current selector, like this:

$(function() {
  $('#menu li:even').hover(function() {
    $(this).toggleClass('pretty-hover', 500);
  });
  $('#menu li:odd').hover(function() {
    $(this).toggleClass('pretty-hover_01', 500);
  });
});

I realize the above seems backwards, but :even does select the first element, because it's 0 based, so even selects 0th, 2nd, 4th, etc. I hope you'll agree, makes it a bit easier to maintain :)

Edit based on comments - Since .toggleclass() sticks on quick hovers, here's an alternative that works as expected, just a bit longer:

$('#menu li.post:even').hover(function() {
  $(this).stop().animate({ backgroundColor: '#009FDD', color: '#FFF' }, 500);
}, function() {
  $(this).stop().animate({ backgroundColor: '#FFFFFF', color: '#666' }, 500);  
});
$('#menu li.post:odd').hover(function() {
  $(this).stop().animate({ backgroundColor: '#623A10', color: '#FFF' }, 500);
}, function() {
  $(this).stop().animate({ backgroundColor: '#FFFFFF', color: '#666' }, 500);  
});
like image 157
Nick Craver Avatar answered Sep 20 '22 16:09

Nick Craver