What I want to achieve is when users clicks on a link is for the button clicked to stay the color and not fade out when the mouse moves out of hover state.
If possible only one button receive the click color at a time.
Any help is appreciated! There is a link to JS Fiddle at the bottom.
HTML
<ul>
<li><a href="#" class="slide">1</a></li>
<li><a href="#" class="slide">2</a></li>
<li><a href="#" class="slide">3</a></li>
<li><a href="#" class="slide">4</a></li>
</ul>
CSS
.slide {
padding:20px 20px 20px 20px;
margin:20px;
background-color:#999;
}
ul li {
float:left;
}
Jquery
$('.slide').click(function() {
$(this).css("background-color", "#f09");
});
$('.slide').hover(function() {
$(this).animate({
backgroundColor: '#000'
}, 300);
}, function() {
$(this).animate({
backgroundColor: '#999'
}, 200);
});
JS Fiddle Link
http://jsfiddle.net/coltanious/wNTs7/9/
Changing your code like the following should work.
In your code you're overwriting the background colour when you set the animated hover.
All you need to do is set a flag, to ensure this doesn't happen. When the element is clicked, I add a class to set its style, this also acts as a flag to ensure the colour doesn't change on hover.
$('.slide').click(function() {
$(".slide").each(function(i,elem) { // clear the style first
$(elem).removeClass("clicked");
});//so only ONE element is coloured SELECTED
$(this).addClass("clicked");//add the "selected" colour
});
$('.slide').hover(
function() {
if(!$(this).hasClass("clicked")) //check flag
{//then hover
$(this).animate({
backgroundColor: '#000'
}, 300);
}
},
function() {
if(!$(this).hasClass("clicked")) {
$(this).animate({
backgroundColor: '#999'
}, 200);
}
}
);
You css would need to have
.clicked
{//set !important on the style so it overrides the .slide bg colour
background-color:#f09 !important;
}
Updated fiddle: http://jsfiddle.net/wNTs7/23/
See this version for one way to do it:
This also solves the problem of animation "overwriting" your set color.
Here's the example code - change as needed:
function setColor() {
$(this).css("background-color", "#f09");
}
$('.slide').click(function() {
setColor.call(this);
$(this).attr('stay-like-this', 'yes');
});
$('.slide').hover(function() {
if($(this).attr('stay-like-this') != 'yes') {
$(this).animate({
backgroundColor: '#000'
}, 300, 'swing', setColor);
}
}, function() {
if($(this).attr('stay-like-this') != 'yes') {
$(this).animate({
backgroundColor: '#999'
}, 200, 'swing', setColor);
}
});
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With