hey guys, something is kind of wrong with my script. i'm having a div #searchbox and a div #searchboxtrigger.
Fairly simpel: the #searchbox is hidden with display:none. if the #searchboxtrigger is clicked i'm slidingDown the #searchbox AND I'M SAVING A COOKIE. If i click the #searchboxtrigger again the #searchbox is slidingUp again and the cookie is set to null.
therefore i'm using the jquery cookie plugin.
onload i check if the cookie is set because if it's set the #searchbox should be visible when the page loads. if the #searchbox slidesUp again and the cookie is set to null, i don't want it to be visible.
onload:
if($.cookie('search_visible') == 'true'){
$('#searchbox').show();
console.debug('is visible');
}else{
$('#searchbox').hide();
console.debug('is hidden');
}
onclick:
$('#searchboxtrigger').click( function() {
if($.cookie('search_visible') == 'true') {
$('#searchbox').slideUp('fast');
$.cookie('search_visible', null);
console.debug('is hidden');
} else {
$('#searchbox').slideDown('fast');
$.cookie('search_visible', 'true');
console.debug('is visible');
}
});
can 开发者_开发问答you guys see anything weird? sometimes the #searchboxtrigger just doesn't respond and the console fires "is hidden" a dozen times till i reload. is there anything i forgot to think of?
Just read the cookie to get the initial status, and write it when the status changes. Do not use it for the internal state, you keep a JavaScript var for that.
I'd also suggest making searchboxtrigger an <a>
instead of a <div>
, and precalculating jQuery DOM elements you are reusing.
Something like this:
$(document).ready(function() {
var searchVisible = $.cookie('search_visible') == 'true';
var searchBox = $('#searchbox');
if (searchVisible) {
searchBox.show();
} else {
searchBox.hide();
}
searchBox.click(function() {
if (searchVisible) {
searchBox.slideUp('fast');
$.cookie('search_visible', null);
searchVisible = false;
} else {
searchBox.slideDown('fast');
$.cookie('search_visible', 'true');
searchVisible = true;
}
return false;
});
});
精彩评论