Let say i've the following function
<script language="javascript">
function myfunction() {
alert("This function was successfully triggered");
}
myfunction(); // trigger it
</script>
I'd like to makes it drop cookie with a name and expiration 24 hours and every-time the user trigger the function myfunction();, it will check for cookies exist and valid or not
What i means is something like this scheme
1) var cookie_name = cowboy; // define name
2) Check of cookie with name cowboy exist and valid of 24 hours since today date.
if exist and valid then do nothing
if not exist or not valid then do the alert and drop cookie with name cookie_name for 24 hours and do the alert alert("This function was successfully triggered");
so any help how to rewrite this function to do so.
You can simply use cookies like this
JavaScript Code:
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);
}
}
}
call the function Inside HTML:
<body onload="checkCookie()">
Related
Is it possible to create a session number of page view/visit like PHP, but in JavaScript?
$_SESSION['views'] = 0;
Is it possible to keep track of the number even when user quite the page and get back again?
You could use Cookies. On visit get the cookie and increment it by 1. Or set it to 1 if it doesn't exist
Example:
<p id="yolo"> </p>
<script>
var numberOfVisits = function getCookie('numberOfVisits');
if (numberOfVisits == "")
{
setcookie('numberOfVisits', 1, 100);
}
else
{
numberOfVisits++;
setcookie('numberOfVisits', numberOfVisits, 100);
}
document.getElementById('yolo').innerHTML = getCookie('numberOfVisits');
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 setcookie(name, value, days)
{
if (days)
{
var date = new Date();
date.setTime(date.getTime()+days*24*60*60*1000);
var expires = "; expires=" + date.toGMTString();
}
else
{
var expires = "";
}
document.cookie = name+"=" + value+expires + ";path=/";added
}
</script>
If you only need the data on the client side then use
window.localStorage, it stores data with no expiration date on the client side and it does not send it to the server on every request like cookies, as explained here.
<script>
var varname = "VISIT_COUNTER";
if (localStorage.getItem(varname) === null) {
localStorage.setItem(varname, 1);
} else {
var visits_count = parseInt(localStorage.getItem(varname)) + 1;
localStorage.setItem(varname, visits_count);
console.log("Total visits: " + visits_count);
}
</script>
<script type="text/javascript">
function WorldwideSellingModelCookie(){
days=7;
myDate = new Date();
myDate.setTime(myDate.getTime()+(days*24*60*60*1000));
document.cookie = 'WorldwideSellingModelCookie=Accepted; expires=' + myDate.toGMTString();
}
function CheckCookies(){
var worldwideSellingCookie = getCookie("WorldwideSellingModelCookie");
if (worldwideSellingCookie == "Accepted")
{
jQuery(".alert-worldwide").hide();
}
}
CheckCookies();
</script>
Hi,
The cookie is being created, I am just unsure how to get my if statement to work within my CheckCookies function so that it hide a div on the page?
I am recieving the following console error:
Uncaught ReferenceError: getCookie is not defined
Can anyone advise what I am doing wrong?
Thanks
UPDATE:
<script type="text/javascript">
function WorldwideSellingModelCookie(){
days=7;
myDate = new Date();
myDate.setTime(myDate.getTime()+(days*24*60*60*1000));
document.cookie = 'WorldwideSellingModelCookie=Accepted; expires=' + myDate.toGMTString();
}
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 CheckCookies(){
var worldwideSellingCookie = getCookie("WorldwideSellingModelCookie");
if (worldwideSellingCookie == "Accepted")
{
jQuery(".alert-worldwide").hide();
}
}
CheckCookies();
</script>
Just added the function to check the cookie and seems to be working now, however the div appears for a split second before hiding. Is there any way to stop this from happening?
These are the functions I use to add, get, or clear cookies in JavaScript.
/* function creates cooke with random key */
function setCookie(inputs) {
/* cookie name */
var name = (inputs[0]) ? inputs[0] : "key" + document.cookie.length;
/* cookie expire in 120 seconds */
var date = new Date();
date.setTime(date.getTime() + (120 * 1000));
var expires = "; expires=" + date.toGMTString();
/* sets cookie */
document.cookie = name + "=" + inputs[1] + expires;
};
/* get the cookie based on input */
function getCookie(input) {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var name = cookies[i].split('=')[0].toLowerCase();
var value = cookies[i].split('=')[1].toLowerCase();
if (name === input) {
return value;
} else if (value === input) {
return name;
}
}
return "";
};
/* destroy me cookies (well only delete javascript cookies) */
function clearCookies(elements) {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf('=');
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
$(elements[0]).val('');
$(elements[1]).val('');
$(elements[2]).val('');
$(elements[3]).html('No Cookie');
};
Also this is a good Document.cookie MDN
I have the below javascript function that currently runs on every visit. I do not want to spam our visitors with this popup on every visit so I am trying to get my head around cookies and running this once a week.
setTimeout(function() {
jQuery(document).one('mouseleave', function() {
console.log('mouse left');
jQuery('.open-popup-link').magnificPopup('open');
});
}, 10000);
I placed this within a cookie function that I found on here however nothing runs and no errors in the console.
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;
}
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 pinball = getCookie("pinball");
if (pinball === "") { // Cookie not set
setTimeout(function() {
jQuery(document).one('mouseleave', function() {
console.log('mouse left');
jQuery('.open-popup-link').magnificPopup('open');
});
}, 10000);
setCookie("pinball", "seen", 7);
}
}
What have I missed or need to do to make this run?
I agree with #MysterX about local storage, but to answer your question - from reading your code - there does not seem to be a call to trigger checkCookie() which means that there are no errors because the function has not run.
You should probably have:
$(document).ready(function(){
checkCookie()
})
also you have a typo in the first section of code and in the checkCookie function as well - same error - you have :
jQuery(document).one('mouseleave', function() {...
and it should be .
jQuery(document).on('mouseleave', function() {...
Using localStorage, only call checkSeen once per page load, or execute it inside of setInterval for browsers that never close.
function popup() {
...
}
function updateSeen() {
var sec = Math.round(Date.now()/1000);
localStorage.setItem("seen", sec);
return sec;
}
function checkSeen() {
var seen = localStorage.getItem("seen") || updateSeen();
var now = Math.round(Date.now()/1000);
var week = 604800;
if ((now - seen) >= week) {
updateSeen();
popup();
}
}
checkSeen();
I started by setting some cookies on my website, the cookie captures the name of the user and displays greetings messages. It was created using guides from w3schools. It worked fine. However, when I try to perform the following String Validation for a test, the cookies magically stop working - no name capture, no greetings messages. The validation also doesn't work and never has. Why? Help? Need some code to make this work:
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 title = cname + "=";
var cookie_array = document.cookie.split(';');
for(var i=0; i<cookie_array.length; i++) {
var check = cookie_array[i];
while (check.charAt(0)==' ') check = check.substring(1);
if (check.indexOf(title) != -1) {
return check.substring(title.length, check.length);
}
}
return "";
}
function checkCookie() {
var name=getCookie("name");
if (name != "") {
alert("Welcome again " + name);
} else {
name = prompt("Please enter your name:","");
if (name != null && name != "") {
setCookie("name", name, 30);
}
}
}
function RemoveC() {
document.cookie = "name=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
}
function Test(str) {
return /^[a-zA-Z()]+$/.test(str)
}
function Validation() {
document.getElementById("vresult").innerHTML = "";
PetName = prompt("Please enter your favourite pet's name:","");
var T = Test(PetName);
if (T == false) { document.getElementById("vresult").innerHTML = "You did not enter a valid name!"; }
else { document.getElementById("vresult").innerHTML = PetName + " is a lovely name, good choice!!"; }
}
Huh, this is strange but, I've been trying to get this to work for the past two days now and I just went back to my website tab and refreshed and everything worked for the first time. Weird, why is that?
<script type="text/javascript">
jQuery(document).ready(function(){
if (document.cookie.indexOf('visited=false') == -1)
{
var fifteenDays = 1000*60*60*24*30;
var expires = new Date((new Date()).valueOf() + fifteenDays);
document.cookie = "visited=true;expires=" + expires.toUTCString();
$.colorbox({width:"400px", inline:true, href:"#exestylepopups"});
}
});
</script>
What's wrong with my above code my facebook like popup is called every time the page is loaded in my blog. I just to show only one time every 30 days.How i can do that?
Your particular implementation looks like it has you checking the cookie for 'visited=false', but setting the cookie to 'visited=true' so your if statement will never match.
I'd suggest you use a proven set of cookie manipulation functions and then your task will be pretty easy.
Here are the cookie functions I use when my environment doesn't already have them:
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
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,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
Once you have those, you can do this:
jQuery(document).ready(function() {
var visited = readCookie('visited');
if (!visited || visited !== "true") {
createCookie('visited', "true", 30);
$.colorbox({width:"400px", inline:true, href:"#exestylepopups"});
}
});