0

I have:

<div class="button" id="button1">Click</div>
<div class="button" id="button2">Click</div>

and the JS

$('.button').click(function(){
    $('.button').removeClass('selected');
    $(this).addClass('selected');
});

CSS

.selected {

background-color: green;

}

Can I 'animate' the applying of the class 'selected'? I.e on a click of the div, the background slides in from the right or fades in for example? Is there a decent plugin available that could achieve this? Is there are a CSS workaround/method?

OliverJ90
  • 1,291
  • 2
  • 21
  • 42
  • 1
    Possible duplicate: http://stackoverflow.com/questions/1248542/jquery-animate-with-css-class-only-without-explicit-styles – pete Jul 11 '14 at 09:21

2 Answers2

2

Simply use CSS3

-webkit-transition: all 0.5s ease;
-moz-transition: all 0.5s ease;
-o-transition: all 0.5s ease;
transition: all 0.5s ease;

Example http://jsfiddle.net/tw16/JfK6N/

if you don't want to use CSS3 to support older Browsers use the done() callback of animate

$('.button').click(function() {
  $('.button').removeClass('selected');
$(this).animate({
  backgroundColor: green
}, 1000, "linear", function() {
  $(this).addClass('selected');
});
});
M41DZ3N
  • 326
  • 1
  • 4
  • 19
0

You can use css3 for that. Use transition to background color change.

-webkit-transition: all 0.3s ease;                  
-moz-transition: all 0.3s ease;                 
-o-transition: all 0.3s ease;   
-ms-transition: all 0.3s ease;          
transition: all 0.3s ease;

Here is the example with your code: http://jsfiddle.net/mm9mV/

Gyula Sz.
  • 202
  • 1
  • 5
  • Thanks, do you know if you can say, "slide in from right" using css3? – OliverJ90 Jul 11 '14 at 09:31
  • I don't know exactly what you want. To slide in all the buttons, or a transition effect that's filling up the background from left to right. – Gyula Sz. Jul 11 '14 at 11:36
  • No worries, I got it sorted using a background image and `-webkit-transition:background-position 0.4s ease;` and then using .addClass to change the background position. – OliverJ90 Jul 11 '14 at 12:36