Reputation: 672
I am using jQuery.cookie plugin to keep same user info because I have to load a different div every time page loads from same user. I have a code for first and second visit but I need for 3rd visit also and back to first after that.
<script>
jQuery(document).ready(function (){
if (jQuery.cookie('firstVisit') === undefined){
jQuery.cookie('firstVisit', 'value');
alert('first');
} else {
alert('second');
}
});
</script>
Upvotes: 3
Views: 512
Reputation: 3112
If you don't mind storing a number instead of a word in your cookie you could store the actual visit number. The use the modulus operator which will give you the remainder of the actual number of visits divided by three. This you can then use to display your div
's (0, 1 or 2 for your requirements).
If you find later on that you have more div
's that you want to show you just need to increase the number in the modulus operation.
This method also gives you the added bonus that you could use this down the line to see how often individuals actually visit your site(provided they don't clear their cache too often).
<script>
jQuery(document).ready(function (){
var actualVisitNo = 0
if (jQuery.cookie('Visit') !== undefined){
actualVisitNo = jQuery.cookie('Visit');
var visitNo = actualVisitNo % 3;
alert("Visit No " + (visitNo + 1));
jQuery.cookie('Visit', actualVisitNo + 1)
});
</script>
Upvotes: 1
Reputation: 5832
A flexible solution:
<script>
var visits = [];
visits["1"] = { visit: "first", action: "divId1" };
visits["2"] = { visit: "second", action: "divId2" };
visits["3"] = { visit: "third", action: "divId3" };
var maxVisits = "3";
var divClass = "action";
jQuery(document).ready(function () {
// Hide all div with class action
$("." + divClass).hide();
if (jQuery.cookie('visits') === undefined) {
alert(visits["1"].visit);
jQuery.cookie('visits', '1');
//Action - Show the right div
$("#" + visits["1"].action).show();
} else {
if (jQuery.cookie('visits') < maxVisits) {
var currentVisit = (parseInt(jQuery.cookie('visits')) + 1).toString();
alert(visits[currentVisit].visit);
jQuery.cookie('visits', currentVisit);
//Action - Show the right div
$("#" + visits[currentVisit].action).show();
} else {
alert(visits["1"].visit);
jQuery.cookie('visits', '1');
//Action - Show the right div
$("#" + visits["1"].action).show();
}
}
});
</script>
Upvotes: 2
Reputation: 5745
To make this, use a Switch statement. It is possible to check each value of your cookie.
<script>
jQuery(document).ready(function (){
if (jQuery.cookie('Visit') === undefined){
alert("first")
jQuery.cookie('Visit', 'first');
// action here
}else{
switch jQuery.cookie('Visit'){
case "first":
alert("second")
jQuery.cookie('Visit', 'second');
// action here
break;
case "second":
alert("third")
jQuery.cookie('Visit', 'third');
// action here
break;
case "third":
alert("first")
jQuery.cookie('Visit', 'first');
// action here
break;
}
}
});
</script>
Upvotes: 2