toggle function happening on second click
function toggleDiv()
{
$('#myDiv').toggle(function()
{
$('.pnlMyarea').slideDown();
$('#separator')开发者_开发技巧.hide();
$('#manualInsert').css('margin-top', '15px');
},
function()
{
$('.pnlMyarea').slideUp();
$('#separator').show();
$('#manualInsert').css('margin-top', '42px');
});
}
i am using this function to toggle my panel but this is happening on the second click not on the first what is the error.
Switch the two functions around
Well, there are some uncertainties in toggle functions. Not by design or feature, but by way we use it. I have myself faced this issue many times, as in like, if I set toggle visibility handler on ahref click, and some other action hide it/show it by some other event like ajax load, toggle will not keep track of it, it will do what it is supposed to do, i.e. alternate action to previous. Also, you have to maintain the sequence of both toggling functions, yourself.
So for toggling requirements like such hide/show, I drilled down a much more obvious and controlled solution. Check the code. This way I can show/hide even by some other event and it will be tracked commonly by a class showing
. Helpful in long run and when you have alot of events handling on page. Trust me.
function toggleDiv(div)
{
if($(div).hasClass('showing'))
{
$('.pnlMyarea').slideUp();
$('#separator').show();
$('#manualInsert').css('margin-top', '42px');
$(div).removeClass('showing');
}
else
{
$('.pnlMyarea').slideDown();
$('#separator').hide();
$('#manualInsert').css('margin-top', '15px');
$(div).addClass('showing');
}
}
or simply
function toggleDiv()
{
if($('.pnlMyarea:visible').length > 0)
{
$('.pnlMyarea').slideUp();
$('#separator').show();
$('#manualInsert').css('margin-top', '42px');
}
else
{
$('.pnlMyarea').slideDown();
$('#separator').hide();
$('#manualInsert').css('margin-top', '15px');
}
}
Try this;
$(document).ready(function() {
$('#myBtn').click()(function(){
$('#myDiv').toggle(function()
{
$('.pnlMyarea').slideDown();
$('#separator').hide();
$('#manualInsert').css('margin-top', '15px');
},
function()
{
$('.pnlMyarea').slideUp();
$('#separator').show();
$('#manualInsert').css('margin-top', '42px');
});
});
});
精彩评论