Reputation: 85
I have a simple code here
$("#faqs h4").click(function(){
var div=$("div");
var h4=$("h4");
h4.animate({letterSpacing:'0.1em'}, "slow");
});
When the h4 heading is clicked, the letters will space out to 0.1em. Now I can't figure out how to write another code so that it goes back to 0.0em when it is clicked again. Help! Thanks!
Upvotes: 1
Views: 314
Reputation: 24435
Here's one way to do it using an external variable to contain the h4's spacing state:
var spaced = false;
$("#faqs h4").click(function(){
var spacing = spaced ? '0em' : '0.1em'; // decide which spacing to use
spaced = spaced ? false : true; // set state to either or
$(this).animate({letterSpacing: spacing}, "slow");
});
Demo: http://jsfiddle.net/Pyd6e/1/
Edit: as per Josh from Qaribou's comment, I hadn't noticed the way you are selecting your elements. You should be using this
to refer to the current clicked h4 element, otherwise all of your h4s are going to be partying. Updated answer and fiddle.
Upvotes: 2
Reputation: 8793
Here's one way you could do it:
$("#faqs h4").click(function(){
var div=$("div");
var h4=$("h4");
var theSpacing = h4.css('letterSpacing');
if (theSpacing == '0em') {
h4.animate({letterSpacing:'0.1em'}, "slow");
}
else {
h4.animate({letterSpacing: '0em'}, 'slow');
}
});
or another way
var theSpacing = 0; // set a counter var to use as a toggle method
$("#faqs h4").click(function(){
var div=$("div");
var h4=$("h4");
if (theSpacing == 0) {
h4.animate({letterSpacing:'0.1em'}, "slow");
theSpacing += 1; // sets it not equal to 0 so on next click it will run the else statement
}
else {
h4.animate({letterSpacing: '0em'}, 'slow');
theSpacing = 0; // sets it equal to 0 so on next click will run the code in the if statement
}
});
Upvotes: 1