Reputation: 407
Does anyone know how to assign an onClick to an object that performs one action, then when the user clicks on the same object, the action is reversed?
$('#image').click(function() {
$('#foo').css({
'background-color': 'red',
'color': 'white',
'font-size': '44px'
});
});
So clicking on #image will either add the changes to #foo or reverse changes.
Fiddle: http://jsfiddle.net/Sx5yH/804/
Any suggestions?
Upvotes: 1
Views: 2970
Reputation: 8660
http://jsfiddle.net/gb0udnft/1/
You can use a boolean value to determine whether or not it's been clicked, then use a ternary statement to do whatever depending if it's true or false.
(boolean) ? true : false;
You could also use the innate JQuery toggle() function
http://jsfiddle.net/gb0udnft/2/
$('#image').toggle(function() {
// do whatever
}
, function() {
// do whatever
});
or use a css class back and forth by using .toggleClass(), .addClass(), or .removeClass()
Upvotes: 0
Reputation: 875
Specifically in your case - it is better to assign a class to the object. Then you can use the jquery toggle functionality to add/remove the style.
CSS
#image.selected {
background-color: red;
color: white;
font-size: 44px;
}
JavaScript
$('#image').click(function() {
$('#image').toggleClass("selected");
});
Upvotes: 4
Reputation: 193261
Don't manipulate with inline styles directly, this is not very flexible approach. Instead you want to toggle class that holds necessary styles:
$('#image').click(function() {
$('#foo').toggleClass('active');
});
where the class active
is defined like this:
#foo.active {
background-color: red;
color: white;
font-size: 44px;
}
Demo: http://jsfiddle.net/Sx5yH/812/
Upvotes: 5