Reputation: 45
how can I toggle two divs using.toggle I have the following so far:
$('#toggler').change(function() {
$('#div1').toggle();
$('#div2').toggle();
});
toggler is a checkbutton - I want div 1 to appear when true and div 2 to disappear and the opposite to happen when false, any ideas?
EDIT** - I can't use .hide() as if I start the page with the checkbutton selected the toggle will be around the wrong way
Upvotes: 0
Views: 78
Reputation: 17203
You can put a boolean value in the toggle()
var isChecked = $('#toggler').is(':checked');
$('#toggler').change(function() {
$('#div1').toggle(isChecked);
$('#div2').toggle(!isChecked);
});
jQuery documentation -
$( "#foo" ).toggle( showOrHide );
is equivalent to -
if ( showOrHide === true ) {
$( "#foo" ).show();
} else if ( showOrHide === false ) {
$( "#foo" ).hide();
}
Upvotes: 1
Reputation: 18099
Try this fiddle: http://jsfiddle.net/sWJ9u/1/
$(document).ready(function () {
$('#toggler').change(function () {
var input = $(this);
var div = input.is(':checked') ? $('#div1') : $('#div2');
$('div').hide();
div.show();
});
});
Upvotes: 0