Setting up cookie with Javascript - javascript

My js app is an advent calendar where users can open a 'door' on or before today's so the div background image changes.
I would like to set up a cookie so when they return the following day the divs still have the background image in place.
I have set up the cookie and door open code but I'm not sure how to integrate the cookie into the door open function. Any help would be appreciated, many thanks.
Link to App: http://p3.katecooperuk.com
Door Open - select Random background image from Array:
$('.doors').click(function () {
if (today.getMonth() !== 11) {
return;
}
// Check if the date is tomorrow or later
if (+($(this).attr('id').split('dec')[1]) > day) {
// Show image telling user to come back
$(this).css('background-image', 'url(/images/come_back.png)');
return;
}
// Otherwise it is today or earlier
// Select Random Image
var doorImage = getRandomImage(calendarImg);
// Change background image of door that was clicked
$(this).css('background-image', doorImage);
});
Cookie
//on document ready, checks if the cookie is set, and if so, sets the background with it's value
$(function(){
if($.cookie('background-image') != null){
$(this).css('background-image', $.cookie('background-image'));
}
});
// Set cookie
$(function() {
$(this).css('background-image', doorImage);
$.cookie('background-image', doorImage);
});

W3Schools have a great newbie tutorial on cookies here
Basically, what you want to do is set the cookie value to the date it was created and whatever other parameters you want to set when the user comes back (such as the id's of the background images.) Then when the user enters your site you check to see if they have a cookie. If they do, check its date parameter. If it's not today (this is really easy to check with JavaScript) then use your extra parameters to set whatever background you want.
Make sure that whenever they change their backgrounds you reset your cookie data to the current backgrounds.
Hope this helps!
*
From you code, I'm having a hard time understanding exactly what it is you're trying to achieve. Also, I'm looking at your site and I don't see any saved cookies.. Try starting with a simple example, 1 door and 1 cookie. Then do a simple check to see if your cookie is working, for example, set a specific background when a cookie is detected and another if not. Once you successfully manage your cookie you can start making it more complex with more data in it.

Related

Show an alert when image changes on website

I have a GitHub pages site with an image on it. I am trying to have the webpage show an alert whenever I push a change to the website.
My approach so far has been to implement an auto-refresh function:
setTimeout(function(){ location.reload(); }, 60000);
This will auto-update every minute, catching all of the changes that I make. However, I need to show an alert whenever the content of the page changes. It is important to keep in mind that the content will not change upon every refresh -- maybe only every 10 minutes (when I push changes).
I think the way to do this would be to store the name of the image and then look to see if the image name changes at every refresh -- and if the name did change, then show the alert. I have been reading about something called LocalStorage, but I'm not sure how to approach storing the name of a file -- I'm sort of new to JS/HTML.
Is using LocalStorage the best approach to this problem? What are other alternatives/simple ways to implement this on a GitHub page?
Thanks in advance.
If I clearly understand what you need to implement, I'd suggest you to read about MutationObserver in JavaScript. This class tracks all the changes, that are made to binded element. Here's the code and working demo:
<html>
<body>
<p>
Some content
</p>
</body>
<script>
// select the target node
var element = document.getElementsByTagName('p')[0];
// create an observer instance
var observer = new MutationObserver(function(mutations) {
alert("Some changes were made");
});
// configuration of the observer:
var config = { childList: true}; // ,subtree: true, characterData: true
// pass in the target node, as well as the observer options
observer.observe(element, config);
setInterval(function () { // here you can make your changes programatically
element.innerHTML += "New content";
}, 2000)
</script>
</html>
You can also use cookies, i.e. store in a cookie the last "version" of whatever - where "version" can be a string, a number etc.
This has the advantage that it also gets sent to the server, so you may generate the alert layout/code directly on the server.
Check https://github.com/js-cookie/js-cookie for a script simplifying this.
Another alternative is to implement on the server a script that responds whether the content changed. Something like http://foo.bar/changed?lastVer=XXXX which can return a JSON like {changed:true,message:'We have changed the change'}. You would retrieve this via ie. jQuery.getJSON() or vanilla XMLHttpRequest, and if it's the case show the message to the user and then reload the page. But this would require making a runnable server script somewhere.
A third option would be to load the page into, say, a hidden IFRAME, check if the image or content changed and if so transplant only the image - or a certain piece of content - to the main page without refreshing it. Or maybe refresh it. The idea is to load the page in an IFRAME and detect there if something has changed.

Set cookie to a div that is shown after few second of video play?

I have a div element that shows up after 20 second of video play.If you will play the video after 20 second of play a div will shows up. Now I want to set cookie so that if the div have been shown once ,it keeps on showing unless the user clear the cache (cookie logic).
This is what I have tried so far -
http://jsfiddle.net/9L29o365/
How can this be achieved?
Thanks In Advance .
Try this code
set cookie
Cookies.set('div-20sec', 'visited');
get cookie
var val=Cookies.get('div-20sec');
DEMO
You could set the cookie in your onPlayProgress function, and read the same cookie handle in your click play listener:
// set
document.cookie='20secSet=true';
// get
var cookieVal = document.cookie
.split(',')
.indexOf('20secSet=true');
Here's an example using your code.

overlay transparent div one time click

I referred to this thread to get a transparent div to display on top of the web site content and make it disappear when clicking on it...
however, when someone visits a page within the site and they click on the home button they are displayed the transparent div again...
is there a way to have the div appear only one time and do not appear again after they close it?
The best way to do is by setting a cookie. On this way, you can hide it forever, or hide it for a specified time.
document.cookie = "transparentdivShow = false";
And now you can check if this cookie exists, and if so, don't show the div:
if(document.cookie.indexOf("transparentDivShow") >= 0) {
return true; // Don't show it
} else {
return false; // Show the div
}
As the above poster mentioned, you could use a cookie. Alternatively, you could use HTML5 Local Storage! Local Storage allows data to be stored locally within a user's browser.
In this instance, you could have something like a clickcounter that counts to see if the clickcounter is greater than 1. If it is greater than 1, give the div a hidden attribute or just get rid of it.
if (sessionStorage.clickcounter) {
<div hidden> You can't see me. I'm invisible. </div>
} else {
sessionStorage.clickcounter = 1;
<div visible> Hi! I'm not transparent. </div>
}
I hope that this helps. Here's a page with more information on it as well!
http://www.w3schools.com/html/html5_webstorage.asp

Changing link URL after every 5 visits

What I'm trying to accomplish is the following.
I have a link on my website, however I want to change that link after every 5 visits or "page refreshes" by the user and have this loop.
So for example you visit my site and the download button links to a site called "www.site1.com". You refresh my site 5 times and the download button link changes to "www.site2.com". If you refresh it for a 6th time it goes back to the original.
I have not been able to find anything searching through forums that shows what i'm trying to accomplish here. I was just experimenting with a window.onload and setInterval function that changes the link every 5 seconds. Anyway to easily transition this from every 5 seconds to every 5 page visits?
window.onload = function() {
function changeURL(){
document.getElementById("link").href = "www.site1.com";
}
setInterval(changeURL, 5000);
}
You probably want to use JavaScript localStorage or sessionStorage for this. Below is an example of your code using localStorage
Example
window.onload = function()
{
if (localStorage.visits)
{
//If the value is in local storage increase it's value
localStorage.visits = Number(localStorage.visits) + 1;
}
else
{
//If the value isn't in local storage set it to 0
localStorage.visits = 0;
}
//Check if the number of visits is greater than 5 and set the link accordingly
if(localStorage.visits > 5)
{
document.getElementById("link").href = "www.site2.com";
}
else
{
document.getElementById("link").href = "www.site1.com";
}
}
This will only work if their browser supports localStorage. One thing to note as well, the value will not reset if they close the browser page. If you want it to reset when the page is closed, that's what sessionStorage is for.
One more thing to note: The user can clear localStorage by clearing the browser data. If you wanted something that would be even more persistent I don't believe there's a JavaScript only solution (feel free to correct me if I'm wrong about this!)

Change the background image and making it stay on every page

I have created a site where the user can change the image of a page from 4 available imges(which works fine), but when you go to another page, the image changes back to the default.
I'm new at Javascript and trying to create an if else statement but I can't seem to get it to work.
This is something I am after:
if (currentpage == body.style.backgroundImage="url('image1.png')")
{
allotherpages == body.style.backgroundImage="url('image1.png')";
}
else if (currentpage == body.style.backgroundImage="url('image2.png')")
{
allotherpages == body.style.backgroundImage="url('image2.png')";
}
I would appreciate any help or a point in the right direction. Thank you.
You want to save the current user's background when he changes page?
Use cookies to save the current background or store it in a database
Set the background
Save it
When you change page, load the saved background
Save the background name in cookie for exemple:
$.cookie("currentBackground", "image1.png");
When you load your page:
$(document).ready(function(){
var currentBackground = $.cookie("currentBackground");
});

Categories

Resources