webmonkey237 webmonkey237 - 5 months ago 18
jQuery Question

Double click to close side panel

I have been working on a sliding panel using jQuery and jQuery Cookie and its so close to working perfect.

$(function () {
if ($.cookie('myCookieName')) {
$('#slideOut').css('right', '-345px');
$(".slideClose").addClass('hideBtn');
$(".slideOpen").removeClass('hideBtn');
}
});

$('#slideClick').click(function () {
var it = $(this).data('it') || 1;
switch (it) {

case 2:
$(this).parent().animate({
right: '-345px'
}, {
queue: false,
duration: 500
});
$(".slideClose").addClass('hideBtn');
$(".slideOpen").removeClass('hideBtn');
break;

case 1:
$(this).parent().animate({
right: '-0px'
}, {
queue: false,
duration: 500
});
$(".slideOpen").addClass('hideBtn');
$(".slideClose").removeClass('hideBtn');
break;

}
it++;
if (it > 2) it = 1;
$(this).data('it', it);
//$.cookie('myCookieName', '1')
var date = new Date();
var minutes = 1;
date.setTime(date.getTime() + (minutes * 60 * 1000));
$.cookie("myCookieName", "foo", { expires: date });
});


When the panel was closed it took two clicks to open it, someone suggested to change the order of "case 1" and "case 2" which worked however now it takes two clicks to close the panel, any help would be appricated.

Here is the fiddle.

Thanks

Answer

Your issue is your starting case. The reason that it requires 2 clicks is because your first click is to slide the sidebar out, but it's already out.

Change:var it = $(this).data('it') || 1;

To: var it = $(this).data('it') || 2;

Should be good after that.

If you want to make sure you avoid the double click issue with cookies, just make sure you add that case to your cookies function to update the data.

$('#slideClick').data('it', 1);