Check if user has alread visited site in browser session - javascript

So I have this splash screen animation that plays when you visit my website. However, I only want the animation to play the first time you visit it (in the session of course). I tried to make an if else where I check for a cookie called "Session", and if it exists, delete the div containing the animation. If there is no such cookie, create it.
Code:
function session() {
if (document.cookie.indexOf("visited") >= 0) {
$('.splash').remove(this);
} else {
document.cookie = "visited";
}
}
I have never used cookies before so I think I might have made some errors

The portion of your code that deals with cookies should work.
Your problem exists on this line:
$('.splash').remove(this);
Remove this, as it's not necessary.
That line should look like:
$('.splash').remove();
Hope that helps.

Chrome has a security restriction that doesn't allow you to access cookies unless the page is running from a web server. Firefox will work without a web server with cookies. For quick testing of local files I suggest using http-server.
I use the below cookie functions to set cookies easily. The original code comes from w3cschools site with some modifications for IE8 cookie problems.
setCookie = function (c_name,value,exdays) {
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var expires = exdate.toUTCString();
var isIE8 = (document.documentMode !== undefined);
if (exdays == 0) {
expires = (isIE8 == true) ? "" : "0";
}
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+expires);
document.cookie=c_name + "=" + c_value;
}
getCookie = function(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) != -1) return c.substring(name.length,c.length);
}
return "";
}
deleteCookie = function(name) {
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
To check a cookie you could do:
if (getCookie('visited')) {
$('.splash').remove();
deleteCookie('visited');
} else {
setCookie('visited','true',999); //999 days expiration
}

An alternative method:
if (sessionStorage.getItem(‘visited’) !== true){
//code that executed if it is user’s first time
sessionStorage.setItem(‘visited’,true);
}else{
//code that executes if it user has already visited
}

Related

set cookie and show div on first visit then hide

I am trying to set multiple cookies depending on if the div exists via javascript but I have ran into an issue that I cannot figure out. On first visit, I would like to show the div to the user if the div exists then set a cookie (called redCookie) that expires in 3 days. After cookie is set on page refresh div should not be present. After 3 days I would like the div to be shown again redDiv.show().
At the moment the div shows on all page refreshes. The cookie is set but unfortunately it shows every time. Something must be wrong with my if statement but not sure what.
if ((redCookie = true) && (redDiv.length > 0))
Here is a link to js fiddle: https://jsfiddle.net/9uh96bh7/
Here are my functions:
$( document ).ready(function() {
colourCookies();
});
function colourCookies () {
var redCookie = getCookie("red-cookie-name");
var redDiv = $('.red');
var yellowCookie = getCookie("yellow-cookie-name");
var yellowDiv = $('.yellow');
if ((redCookie = true) && (redDiv.length > 0)) {
redDiv.show();
setCookie("red-cookie-name", redCookie, 3);
console.log ('red cookie is set');
} else {
redDiv.hide();
}
if ((yellowCookie = true) && (yellowDiv.length > 0)) {
yellowDiv.show();
setCookie("yellow-cookie-name", yellowCookie, 3);
console.log ('yellow cookie is set');
} else {
yellowDiv.hide();
}
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
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 "";
}
First, the code.
It should be if ((redCookie == true) && (redDiv.length > 0)) not if ((redCookie = true) && (redDiv.length > 0)).
= is assign, == means equal to.
Second, the logic part.
cookie isset -> hide div
cookie is not set -> show div, set cookie
(correct me if I miss understood.)
So the if statement should be:
if (redCookie == true){
//hide div
} else {
//show div
//set cookie
}
Third, you make a mistake when setting cookies.
you should set you cookie like setCookie("yellow-cookie-name", true, 3);
If you use setCookie("yellow-cookie-name", yellowCookie, 3); and yellowCookie is null, this will cause failure to your if statement.
I think problem is with setting cookie, as some of the browser like chrome not sets cookie when you are running it on local, if you host it on server or run it through visual studio, it will work.. Test once with hosting it in iis if possible, else you can use localStorage like below...
$( document ).ready(function() {
colourCookies();
});
function colourCookies () {
removeIfThreeDaysElapsed('red-ls');
removeIfThreeDaysElapsed('yellow-ls');
if (!localStorage.getItem('red-ls')) {
$(".red").show();
localStorage.setItem("red-ls", new Date().toGMTString());
} else {
$(".red").hide();
}
if (!localStorage.getItem('yellow-ls')) {
$(".yellow").show();
localStorage.setItem("yellow-ls", new Date().toGMTString());
} else {
$(".yellow").hide();
}
}
function removeIfThreeDaysElapsed(lsname){
var d1 = localStorage.getItem(lsname);
if(d1){
if(new Date() > new Date(new Date().getTime()+(3*24*60*60*1000))){
localStorage.removeItem(lsname);
}
}
}
You may need to edit the code to handle all the scenarios!
If you able to see the cookie in browser, then please try with check like below...
if (redCookie) {
redDiv.hide();
} else {
redDiv.show();
setCookie("red-cookie-name", true, 3);
}
Because when you are getting value back from cookie its datatype is not boolean, it gets converted to string, so either you check like above or can use redCookie === "true".
Hope this helps you.

Reading Cookie that was saved using javascript into html

I been trying to display Cookies that are saved using javascript into html page
I keep my Javascript in external file and I do not plan on putting this on a server this is for educational client purposes only
I store my cookies using this code Javascript file:`
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
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 "";
}
function checkCookie() {
var user=getCookie("username");
var pass=getCookie("password");
if (user != "" || pass != "") {
alert("Welcome again " + user + " your password is: " + pass);
} else {
user = prompt("Welcome to my Site! Enter your name to begin! :","");
pass = prompt("Make sure to include a password might be useful later! :","");
if ((user != "" && user != null)&&(pass != "" && pass != null)) {
setCookie("username", user, 30);
setCookie("password", pass, 30);
}
}
}
`
and HTML:
<body onload="checkCookie()">
From what I gathered this seems to be working fine since the pop up dialogue says so however
what I want to do is to take this cookie that was saved with alert box and have it displayed on html side so it looks like this
<p>Your cookie is ("Displays the cookie here")</p>
What I tried to do so far is:
<script type="text/javascript">
document.write(getCookie("username"));
</script>
if someone could point me in right directions or say what I'm doing wrong I would be grateful
Add the HTML element of <div id='cookieInfo'></div>
Change your Javascript to:
document.getElementById('cookieInfo').innerHTML = getCookie('userrname');
try this fiddle
this is javascript
$('document').ready(function(){
checkCookie();
document.getElementById("myc").innerHTML = getCookie("username");
})
this is your html
<p>Your name is <span id="myc"></span></p>

Why isn't my cookie storing?

I'm trying to set a cookie on a click event to see if a user has actually clicked the respective button. The button is as follows:
Click here
My js to set the cookie is:
function setCookie(cname, cvalue, exdays){
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires =" + d.toGMTString();
document.cookie = cname +"="+ cvalue + ";" + expires;
}
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 "";
}
Then, I set the cookie on a click event:
$("#modalBTN").click(function(){
var clicked = "clicked";
setCookie("clicked", clicked, 30);
console.log(clicked);
});
My click event works. when I console.log(clicked) I see the cookie value, but when I refresh the page the cookie is no longer there.
I check it by:
if(getCookie("clicked") != ""){
//do something else
}
UPDATE
when I call getCookie("otherCookie") it works. But when I call getCookie("clicked") i get returned null. Am I only allowed to have one at a time?
Try this : https://stackoverflow.com/a/24103596/5445351
You can only use console to test the two functions : createCookie & readCookie
Do :
createCookie('ppkcookie','testcookie',7);
Open another page, check if it's still there :
var x = readCookie('ppkcookie')
if (x) {
console.log("ok");
}
Look if it's not your browser that delete cookies automatically.
I tried with Chrome and IE9.

Javascript is undefined when project is put live

I have the following code, depending on the size of the screen will determine if they are re-directed to the mobile version of the site. Once on the mobile site if they choose to view the desktop version they're then redirected back to the desktop version and a cookie is created, that way they can continue to browse the desktop version without being re-directed again.
$(function() {
if (window.location.href.indexOf(".au") > -1) {
var oldURL = document.referrer;
var t = getCookie("fromMobile");
if (oldURL.indexOf("m.domain") > -1) {
var date = new Date();
var minutes = 30;
date.setTime(date.getTime() + (minutes * 60 * 1000));
document.cookie = "fromMobile=Yes; expires=" + date.toGMTString() + "; path=/";
} else {
if (t == "") {
if (screen.width <= 760) {
window.location = "http://m.domain.com.au/";
}
}
}
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 "";
}
}
});
When I'm running this on local/staging server it works as expected, I don't get any javascript errors, yet when pushed to live the error I get is on the following line
var t = getCookie("fromMobile");
It says getCookie is undefined
I'm uncertain why this works locally and on the staging server, I added alerts inside the getCookie when running locally/staging and I see the alerts....
Move the getCookie definition above "t" var, also you can prefer to use statement
expressions when mixing functions, this will fix the problem with undefined.

initialization and deletion of Cookies

I'm new to javascript and stuck with the following problem with cookies
Problem
The cookie value in the following problem is a name.
I'm trying to display the user's name from the cookie. When the page is opened, if there is a cookie value, then the cookie value must be displayed with appropriate greeting. But if there is no cookie value when the page is opened, a prompt box must pop up asking the name of the user. If the name(cookie value) of the user is displayed wrongly on the page, for instance John opens the page and the name displayed is Paul, then he must click on "click here if You are not Paul" and the cookie must be deleted and John must see a prompt box asking for his name. Then the new cookie value must be whatever John enters in the prompt box
Code
The greetings part is working perfectly. I have the following code.FYI, I'm testing this on a website, not local machine.
<script>
var now = new Date();
var hours = now.getHours();
var name, greeting, count,a;
if(hours < 12)
{
greeting = "Good Morning";
}
else
{
if(hours < 18)
{
greeting = "Good Afternoon";
}
else
{
greeting = "Good Evening";
}
}
if(document.cookie)
{
var newCookie = document.cookie;
var cookieVals = newCookie.split("=");
name = cookieVals[1];
}
else
{
name = window.prompt("Please enter your name","name");
document.cookie = "name=" + name;
}
a = greeting + " " +name + ", Welcome to Survey Page! </h1>" + "<a href = '#' onClick='return false;' onMouseDown='wrongPerson()'> " +"Click here if you are not " + name + "</a>";
function wrongPerson()
{
document.cookie= "name=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
location.reload();
}
<p><span id="verify"></span></p>
<script>document.getElementById("verify").innerHTML = a;</script>
Output
I'm getting the following output
Good Evening 74bec77-148138c40e3-42e9b6fa-5; _ga, Welcome to Survey Page! Click here if you are not 74bec77-148138c40e3-42e9b6fa-5; _ga
Nothing happens when I reload the page or when I click on the link "Click here if you are not 74bec77-148138c40e3-42e9b6fa-5; _ga".
Can someone enlighten me on this?
Your javascript :
if(document.cookie)
{
var newCookie = document.cookie;
var cookieVals = newCookie.split("=");
name = cookieVals[1];
}
checks that is there anything in the cookie and if it is then it will not ask for new name. When the user clicks on I am not ... then The function wrongPerson() sets the cookie to "name=........" which when compare at starting by your if will always return true because
In javascript non zero values are TRUE
So it will think that a user is present. If you will make the function wrongPerson() make the cookie 0 or "" , then the if will get FALSE and the statement (used to ask for name) will get executed.
Fixed Function:
function wrongPerson()
{
document.cookie= "";
location.reload();
}
Create / Call functions it is much easier to understand. source
<!DOCTYPE html>
<html>
<head>
<script>
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
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) != -1) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user=getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
</script>
</head>
<body onload="checkCookie()">
</body>
</html>

Categories