Reputation: 338
I'm trying to create a cookie, so if:
"Toggle" is pressed once a snow storm effect will stop and also generate a cookie so if the user refreshes the page, it will not run. And if they "Toggle" it again the snow storm effect will start and the cookie gets deleted.
At the moment, i have looked at http://www.w3schools.com/js/js_cookies.asp and i need to use the following functions:
document.cookie="name";
function get_cookie(name){
var x = name;
}
function delete_cookie( name ) {
document.cookie = name;
}
So i can have something like in pseudo code :
$("#Snow").click(function () {
snowStorm.toggleSnow()
// Generate a cookie here and returns it //
// Selected again, cookie is deleted //
});
$(document).ready(function(){
$("#Winter").click(function(){
// Gets the cookie and doesn't run the snowStorm.resume
// If no cookie, runs it.
snowStorm.resume()
});
Could anyone please show me an example of creating a cookie when clicked and deleted when clicked again?
I'm not sure how to do this step. I thought of doing using a boolean variable and alter changing , when clicked X sets to true, if clicked again X is set to false - where i then can have a method for deleting or setting.
Upvotes: 0
Views: 509
Reputation: 17371
To make it easier, you can create it once and toggle its value (rather than its existence) to turn on/off the snow.
You can try this:
// this getCookie() function is copied from W3Schools
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
// initialization
var on = getCookie("snow");
if(on == "") {
document.cookie = "snow=true";
start();
} else {
(on == "true") ? start() : stop();
}
// toggling
$("#Winter").click(function() {
if(getCookie("snow") == "true") {
stop();
document.cookie = "snow=false"; // overwrite the cookies to change them
} else {
start();
document.cookie = "snow=true";
}
});
See the working example on JSFiddle.net.
Upvotes: 1