I am trying to write a cookie based menu which contains three options (three links). Now I want that when a user gets on the site, they must have to choose one of the three options. The user’s selection may be store in a cookie so that next time when he arrives at the same site, he does not have to make the selection again and he must be directed automatically to his previous selection.
This is my code for that
</style>
<!-- style Develpor page ends here-->
<script src="jqery1.8.js"></script>
<script type="text/javascript">
var val;
$(document).ready(function (e) {
$('.nav a').click(function (event) {
event.preventDefault();
val = $(this).index();
if (val == 0) {
$('#hide_main').hide();
$('.main_BSNS').animate({
opacity: "show",
height: "400px"
}, 'slow')
} //if val==0 ends here
else if (val == 1) {
$('#hide_main').hide();
$('.main_ACTNT').animate({
opacity: "show",
height: "400px"
}, 'slow')
} else if (val == 2) {
$('#hide_main').hide();
$('.main_devp').animate({
opacity: "show",
height: "400px"
}, 'slow')
}
});
});
<!--cookies starts here-->
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function checkCookie() {
var username = getCookie("BSNS");
if (username != null && username != "") {
$('#hide_main').hide();
$('.main_BSNS').animate({
opacity: "show",
height: "400px"
}, 'slow')
} else {
username=val;
alert(val);
if (username != null && username != "") {
setCookie("BSNS", username, 365);
$('#hide_main').hide();
$('.main_BSNS').animate({
opacity: "show",
height: "400px"
}, 'slow')
}
}
}
<!--cookies ends here-->
</script>
Now function checkCookie() is called by body onload="checkCookie()" and the alert returns the value of val as undefined I know this is because the checkCookie() is being loaded before document.write but I don’t know how to overcome this difficulty.
Hey guys check this out…i made a new code and that did work for me…i am putting it here so that people seeking for events like me may find it helpful….
window.onload=checkCookie();// this code will loads the function checkCookie right after the window is opened…
Now this checkCookie() function will be called by body onload=”checkCookie()”….i just put comments there to show the working of the co