Phill Pafford Phill Pafford - 2 months ago 8
jQuery Question

jQuery toggle passed boolean false first has different transition

Here is a working example: http://jsfiddle.net/FzZwt/8/

If I pass false to the toggle() first the transition is set to slow
If I pass true to the toggle() first the transition is not set

Can I pass a transition with a boolean in the toggle()?

Example:

var show = true;
$('#elem').toggle(show, 'slow');


HTML

<div data-role="page">
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal">
<div>Boolean Test 1 - Passing TRUE first</div>
<input type="radio" name="boolean" id="true" value="true" />
<label for="true">Yes</label>
<input type="radio" name="boolean" id="false" value="false" checked="checked"/>
<label for="false">No</label>
<div class="hidden" name="hidden_div" id="hidden_div">Show Me!!!</div>
</fieldset>
</div>

<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal">
<div>Boolean Test 2 - Passing FALSE First</div>
<input type="radio" name="boolean2" id="true" value="true" />
<label for="true">Yes</label>
<input type="radio" name="boolean2" id="false" value="false" checked="checked"/>
<label for="false">No</label>
<div class="hidden" name="hidden_div2" id="hidden_div2">Show Me!!!</div>
</fieldset>
</div>

</div>


JS

$(".hidden").hide();

$("[name=boolean]").change(function() {
var show = $('input[name=boolean]:checked').val() == "true";
alert('Passing first: '+show);
$("#hidden_div").toggle(show);
});

$("[name=boolean2]").change(function() {
var show = $(this).val();
alert('Passing First: '+show);
$("#hidden_div2").toggle(show);
});

Answer

You're passing string values when it expects either a boolean or an animation speed (either a number or one of the values that translates to numbers).

If you want to pass booleans, you'll need to cast them as Tomalak mentions

I made a couple of changes; is this what you're looking for?

$(".hidden").hide();

$("[name=boolean]").change(function() {
    var show = ($('input[name=boolean]:checked').val() == 'true') ? true : false;
    $("#hidden_div").toggle(show );
});

$("[name=boolean2]").change(function() {
    var show = ($(this).val() == "true") ? true : false ;
    $("#hidden_div2").toggle(show );
});

http://jsfiddle.net/FzZwt/11/