Run a function if a cookie exists - javascript

Okay, I'm new to javascript coding, cookies etc., and I can't quite find the answer to my problem on the net. I'm trying to create a site that has a div that displays some helpful information at the top.
<div id="helpdiv">
<!--This content shows only on web browsers Internet Explorer 6/7/8/9/10/11 and Microsoft Edge.-->
Looks like your using Internet Explorer/Edge. This site is optimized when "Compatibility Mode" is disabled. Thank you!
</div>
I found some code that I can use that will show this div for 8 seconds, then disappear. But I want this to only show up once.
function closeHelpDiv(){
document.getElementById("helpdiv").style.display=" none";
}
// close the div in 8 secs
window.setTimeout( closeHelpDiv, 8000 );
I figured if a cookie was used, then the browser could check for that cookie, and if it existed, then it wouldn't need to show the div. Only the first time they visited the site.
So here's the flow I'm trying to acheive:
Check for a cookie named “helpText”
If the cookie doesn’t exist:
I want to run a function that hides a div (id="helpdiv") after 8 seconds of showing.
Here is some code I found that hides a div:
function closeHelpDiv(){
document.getElementById("helpdiv").style.display=" none";
}
// close the div in 8 secs
window.setTimeout( closeHelpDiv, 8000 );
I then want to set a site cookie called ”helpText” so that next time they visit the site, the function won’t run again.
If cookie exists:
I want the div with an Id of “helpdiv” to have the style=“display:none;”
If I need to add anymore code, please let me know and I can explain more. Any help would be a life saver!!

You can check for cookies on the current web document like this:
document.cookie
So if you are planning to check for a specific string you could do an indexOf("") with the word you are looking for and validating if the index is more than 0.
if(document.cookie.indexOf("helpText") > 0 ){
the cookie was found, so your function should be here
}else{
cookie not found
}
Probably is better to do a search over Stackoverflow because there are a lot of answers about cookies and javascript:
Here It's a full answer about this:
Check if cookie exists else set cookie to Expire in 10 days

Extending on Lemmy's answer, this is what you need:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var myCookie = getCookie("helpText");
if (typeof myCookie === 'undefined') {
// close the div in 8 secs
window.setTimeout( closeHelpDiv, 8000 );
}
function closeHelpDiv(){
document.getElementById("helpdiv").style.display=" none";
}
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
});
</script>
Here is the updated script for your wordpress environment:
<script type="text/javascript">
jQuery(document).ready(function($){
var myCookie = getCookie("helpText");
if (typeof myCookie === 'undefined') {
// close the div in 8 secs
window.setTimeout( closeHelpDiv, 8000 );
//setTimeout(closeHelpDiv, 2000);
}
function closeHelpDiv(){
document.getElementById("helpdiv").style.display=" none";
}
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
});
</script>
In Wordpress you must use change the $ sign with jQuery and pass the $ sign into the function. The dollar sign in $(document).ready(function(){}); is not used for compatibility with other libraries.

try
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
from
Get cookie by name
Use it to check whether the cookie exists or not.
In your code you can easily
if(getCookie('helpText')!=''){
$('selector').css('attrib','prop');
}

So you need to set a cookie after displaying banner to user on her first visit -
function closeHelpDiv(){
document.getElementById("helpdiv").style.display=" none";
document.cookie="visitedBefore=true; expires=1 Jan 9999 12:00:00 UTC; path=/";
}
check with following code if that user already visited your site
function showBanner(){
// check if visited Earlier
if(!getCookie('visitedBefore'))){
window.setTimeout( closeHelpDiv, 8000 );
}
}
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
showBanner();
So you are doing all things correct just use cookies as described above.

Related

JS - Cookie management

I made this little code using JS to disable cookies:
$(document).ready(function() {
var cookie_settings = getCookie("cookie-settings"); //Main cookie which contains cookie preferences
var cookie_selector = document.getElementById("cookie-selector"); //Modal for cookie selection
var g_recaptcha = document.getElementById("cookie-g-recaptcha"); //Example checkbox cookie
var g_tag_manager = document.getElementById("cookie-g-tag-manager"); //Example checkbox cookie
var messenger_plugin = document.getElementById("cookie-fb-mccp"); //Example checkbox cookie
var g_analytics = document.getElementById("cookie-g-analytics"); //Example checkbox cookie
var cookie_set = document.getElementById("cookie-set"); //Button to save preferences
if (cookie_settings == null) { //Check if main cookie exist
$(cookie_selector).modal({
backdrop: 'static',
keyboard: false
}); //If not exist, open cookie selector modal
} else {
var cookie_settings_raw_values = getCookie("cookie-settings"); //read and save main cookie in var
var cookie_settings_values = cookie_settings_raw_values.split('&'); //save main cookie content in array
if (cookie_settings_values.includes(g_recaptcha.id)) {
//If array contains recaptcha example include it
//for example append in head -> $('head').append('myscript');
}
if (cookie_settings_values.includes(g_tag_manager.id)) {
//same
//for example append in head -> $('head').append('myscript');
}
if (cookie_settings_values.includes(messenger_plugin.id)) {
//same
//for example append in head -> $('head').append('myscript');
}
if (cookie_settings_values.includes(g_analytics.id)) {
//same
//for example append in head -> $('head').append('myscript');
}
//or you can remove else condition and manage this part from php
}
$(cookie_set).click(function() { //on save preferences click
var selected_cookies = [g_recaptcha.id, g_tag_manager.id]; //make array and include required cookies
if (messenger_plugin.checked == true) {
//if messenger plugin example checkbox is checked push it's reference in array
selected_cookies.push(messenger_plugin.id);
}
if (g_analytics.checked == true) {
//same for the other optional checkboxes
selected_cookies.push(g_analytics.id);
}
var expiry_date = new Date();
expiry_date.setMonth(expiry_date.getMonth() + 6); //expiration date 6 months in my case, you can set what you want
document.cookie = document.cookie = "cookie-settings=" + selected_cookies.join('&') + "; expires=" + expiry_date.toGMTString(); //make main cookie with required and optional selected checkboxes (the deadline is 6 months after the creation of the cookie)
location.reload(); //reload page
});
//get cookie by name
function getCookie(name) {
var document_cookie = document.cookie;
var prefix = name + "=";
var begin = document_cookie.indexOf("; " + prefix);
if (begin == -1) {
begin = document_cookie.indexOf(prefix);
if (begin != 0) {
return null;
}
} else {
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = document_cookie.length;
}
}
return decodeURI(document_cookie.substring(begin + prefix.length, end));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
My question is it enough to disable third-party cookies?
Not including the scripts if the user does not accept cookies, do the stored ones become useless? Does the site comply with the GDPR?
If not, do you have any other valid alternative to propose that is not the use of third party codes?
Most of the websites, which are trying to be GDPR compliant are not loading any of these scripts by default (as you probably do). First they show a popup, if a user wants to load e.g. tracking cookies and if the user agrees they will be loaded. The configured setting which services should be loaded / what the user has selected will then be stored either in a cookie or e.g. the localStorage.
So yes, your site seems to be GDPR compliant when we take a look at the approach how you load the external scripts.
If you’re talking about deleting them, set it again with the expiry date before today.

How can I stop a background video playing every time the user returns to the home page?

I have been handed a design which requires a background video to load when the users hits the home page. I realise that this isn't best practice, but the design has been signed off by the client, so trying to develop a decent solution for it. I have video in place and it is working nicely.
I have also been asked to ensure that the video only loads once when the user visits the site and when they navigate about the site, if they return to home, the video shouldn't play again.
I have been searching about the web, but can't find a precedent for this. Could anyone suggest a possible solution for this to work? Or some documentation that I could visit to source one?
The site is written with HTML, CSS and JQuery.
I appreciate that there isn't any code to see, but any suggestions would be much appreciated.
Thank you to anyone who stumbles across this.
Use localStorage or sessionStorage:
Supposing you have a video element with an id, e.g.:
<video id="myVideo">...</video>
Your script might look something like this:
if (!localStorage.getItem('alreadyPlayedVideo')) {
const myVideo = document.getElementById('myVideo');
myVideo.play();
localStorage.setItem('alreadyPlayedVideo', true);
}
It would look the same with sessionStorage. The primary difference between the two is that sessionStorage is cleared when the user exits the browser or closes the tab, whereas localStorage persists between sessions.
You have to check if the user was already on the site, so you have to save this data somewhere, data can be saved in session, database, localStorage or in cookies.
Using cookies would be the best option for this scenario. Cookies gets stored on client side and can be used for session and state management
Cookie usage with JS
function setCookie(cookieName, cookieValue, expireDays,isGlobal) {
var expireDate = new Date();
expireDate.setTime(d.getTime() + (expireDays*24*60*60*1000));
var expires = "expires="+expireDate.toUTCString();
if(isGlobal){
document.cookie = cookieName + "=" + cookieValue + "; " + expires+"; path=/";
}else{
document.cookie = cookieName + "=" + cookieValue + "; " + expires;
}
}
function getCookie(cookieName) {
var name = cookieName + "=";
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(cookieName) {
if (getCookie(cookieName) != "") {
return true;
} else {
return false;
}
}
$(document).ready(function(){
if(checkCookie('visited')){
//Stop playing video
}else{
setCookie('visited',1,3,false);
//Play video automatically
}
});

Setting basic cookie and alert with cookie value

I'm trying to set a basic cookie. I've left the alert in so I can see if I'm successfully doing so. I want to store the end of the current url. For example, I want to store the MWFhUDfYpc9JYWmyapBDZvVYEz9rkMK6wSGZX4s. from http://www.example.com/index.php?cid=MWFhUDfYpc9JYWmyapBDZvVYEz9rkMK6wSGZX4s.
I've successfully set the cookie as the url on load, but can't get further.
<script type="text/javascript">
function WriteCookie()
{
cookievalue= window.location + ";";
document.cookie="name=" + cookievalue;
alert( cookievalue );
}
</script>
Your trying to activate the window.location which returns the entire path of the current page. This is fine, but it will load the entire string http://www.example.com/index.php?cid=MWFhUDfYpc9JYWmyapBDZvVYEz9rkMK6wSGZX4s rather than just MWFhUDfYpc9JYWmyapBDZvVYEz9rkMK6wSGZX4s. And finally, if your only storing 1 key in your cookie, you do not need a semi-colon at the end of the document.cookie string.
Example jsfiddle:
FIDDLE
Here is a revised code, with some error handling.
<script type="text/javascript">
WriteCookie();
function WriteCookie() {
try {
var splt = window.location.split("=");
document.cookie="name=" + splt[1];
alert(splt[1]);
} catch (err) {
txt = "Error Found\n\n";
txt += "Description: " + err.message + "\n\n";
txt += "Click OK to continue.\n\n";
alert(txt);
}
}
</script>

Loop on back button after re-direction with querystring

The problem:
I need to start with a URL with a query string containing a URL of a second page - http://www.firstURL.com/?http://www.secondURL.com. On the target page of the first URL, the query string is parsed to extract the second URL and the browser is re-directed to the second URL. This is done on $(document).ready so that it's automatic. This all works fine, but of course falls in a hole if the user hits the back button on the second URL. Here's the basic code:
$(document).ready(function() {
var s = location.search;
if(s != '') {
var split = s.split('?');
var loc = split[1].replace('?', '');
location.href = '' + loc + '';
} else {
//do something else on the target page..
}
});
I've tried creating a conditional case where, if the referrer is the 2nd URL (loc in the code above), the re-direction doesn't execute, but it seems that in the case of a re-direction, the back button doesn't return the referrer.
I have to do all this client side - I have no access to the server.
Is there some way to prevent the re-direction triggering on a back button click? Thanks.
Once you hit the second page, set a cookie in your browser indicating that the second page has been visited.
In the first page, before doing the redirection always check whether the cookie is not present.
Instructions on setting a cookie:
<script type="text/javascript">
document.cookie="secondpagevisited=43yj0u3jt;path=/"; //execute this line in the head of second page.
</script>
In first page, check for cookie presence:
<script type="text/javascript">
if(document.cookie.indexOf("secondpagevisited=43yj0u3jt")==-1){
/*do redirection here*/
}
</script>
EDIT: Assuming you control only the first page and not the second page, try this:
<script type="text/javascript">
if(document.cookie.indexOf("secondpagevisited=43yj0u3jt")==-1){
document.cookie="secondpagevisited=43yj0u3jt;path=/";
/*do redirection here*/
}
</script>
I gave Ashish the point for putting me on the right track, but this is my solution which goes one step further:
var s = location.search;
if(s != '') {
var split = s.split('?');
var loc = split[1].replace('?', '');
if (document.cookie.indexOf('redirected=' + loc + '') == -1) {
document.cookie = 'redirected=' + loc + '';
location.href = '' + loc + '';
} else {
var url = location.href.replace('' + s + '', '');
document.cookie = 'redirected=; expires=Thu, 01 Jan 1970 00:00:00 GMT';
history.pushState(null, null, '' + url + '');
}
If the cookie is there, the re-direction doesn't occur, the cookie is removed (in case the user returns to the site that had the original link and clicks it again), and the URL is tidied up by removing the query string.
Thanks for the guidance.

Javascript - checking if cookie exists on page load isn't working for me

I have the follwing code :
<script type="text/javascript">
function myfuncc () {
if (document.cookie.indexOf("visited") >= 0) {
// They've been here before.
alert("hello again");
}
else {
// set a new cookie
expiry = new Date();
expiry.setTime(date.getTime()+(10*60*1000)); // Ten minutes
// Date()'s toGMTSting() method will format the date correctly for a cookie
document.cookie = "visited=yes; expires=" + expiry.toGMTString();
alert("this is your first time");
}
}
</script>
<script type="text/javascript">
window.onload = myfuncc;
</script>
As you can see the window.onload function, I am trying to check if a vistor had already been at the site once the page loads. I am using cookies to do so. Problem is, I can't see the messages I am supposed to. Anyone knows why?
You have to set the expire date using toUTCString() method.
You also have a date object that is not initialized, try this:
function myfuncc () {
if (document.cookie.indexOf("visited") >= 0) {
// They've been here before.
alert("hello again");
}
else {
var expiry = new Date();
expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes
document.cookie = "visited=yes; expires=" + expiry.toUTCString();
alert("this is your first time");
}
}
give this a try:
var testarr = ["knirpsel", "text", "visited=yes"].indexOf("visited");
alert ( testarr );
output is "-1" which means the string "visited=yes" won't be found by search term "visited"
http://jsfiddle.net/m5x3M/
and
What is the best way to get a cookie by name in JavaScript?

Categories

Resources