Reputation: 143
I'm trying to toggle animation of background colour on click (along with form slideToggle), but the first click hides the element (a#opt4) instead of changing the colour. What am I doing wrong?
note: when I'm running single background animate, instead of toggle, it works no problem. I want to remove the colour when user clicks on a link again, though.
$(document).ready(function() {
$('#contact form').hide();
$('a#opt4').click(function(e) {
e.preventDefault();
$('#contact form').slideToggle();
$(this).toggle(function() {
$(this).animate({
backgroundColor: "#99ccff"},500);
},
function() {
$(this).animate({
backgroundColor: "none"},500);
});
});
});
Upvotes: 1
Views: 1287
Reputation: 6512
What jQuery version are you using? As of jQuery 1.8 .toggle()
was deprecated, and 1.9 .toggle()
was removed.
Just so people aren't confused about the toggle animation as apposed to the toggle event.
Note: This method signature was deprecated in jQuery 1.8 and removed in jQuery 1.9. jQuery also provides an animation method named .toggle() that toggles the visibility of elements. Whether the animation or the event method is fired depends on the set of arguments passed.
If you are using 1.9 or above you can try writing your own toggle functionality. Of course this method is basic and could be built upon.
$.fn.toggleState = function (even, odd) {
this.toggled = this.data('toggled') || false;
if (!toggled) {
if (typeof even === 'function') {
even(this);
}
} else {
if (typeof odd === 'function') {
odd(this);
}
}
this.data({ toggled: !this.toggled });
};
Which can be used like so
$('a#opt4').click(function (e) {
e.preventDefault();
$(this).toggleState(function (el) {
el.animate({
backgroundColor: "#99ccff"
}, 500);
}, function (el) {
el.animate({
backgroundColor: "none"
}, 500);
});
});
$.fn.toggleState = function (even, odd) {
this.toggled = this.data('toggled') || false;
if (!this.toggled) {
if (typeof even === 'function') {
even(this);
}
} else {
if (typeof odd === 'function') {
odd(this);
}
}
this.data({ toggled: !this.toggled });
};
Check it out in this JSFiddle
Just a side note, you can also use jQueryUI to animate background color. Which is what's used in the demo.
Upvotes: 1
Reputation: 1218
Use classes to do that...
In css:
.active-link{
background-color: #99ccff;
-moz-transition: all 0.2s linear;
-webkit-transition: all 0.2s linear;
-o-transition: all 0.2s linear;
transition: all 0.2s linear;
}
In your JS:
$(this).toogleClass("active-link");
Upvotes: 1
Reputation: 1891
From the documentation here http://api.jquery.com/animate/ you cannot animate background colors.
From the docs
background-color cannot be - animated -, unless the jQuery.Color() plugin is used)
I've not used it but here is the color plugin they mention.
https://github.com/jquery/jquery-color/
Upvotes: 0