Countdown clock not reset on refresh - javascript

I have a countdown clock here that resets when the page is refreshed. I would appreciate it if someone could help me?
I have included the script below.
<script type="text/javascript">
var ticker = function() {
$("#ticker").css({
left: "120%"
}).animate({
left: "-420px"
}, 6000, 'linear', ticker);
}
ticker();
</script>

Considering you need it to be "running" while user is not in the page, I will point out that Javascript is a client side scripting language Javascript code is run in local side i.e its interpereted by the browser. This makes hard to "keep" track of things if the user refreshes the page until unless you have have stored them somewhere. There can be different approaches for your solution such as:-
LocalStorage
Cookies
Server Side Clock
You can use either of the three. You can use localstorage to save the clock end time and whenever the user refreshes the page get the value from localstorage and start you clock accordingly. Similar approach can be used with cookies. Or you can use some server side code to initialize the clock whenever your page loads the server will set start the clock accordingly. but there can be some lag as mentioned above in comments. So the best approach in my opinion, if you just want to use javascript, would be to use cookies/localstorage to save the exact time when the countdown will reach value 0. So everytime you load into the page, you can get the stored value , and get how long is missing yet and set the clock accordingly.
Some coding
Create a cookie with expiration time:
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;
}
Get a cookie:
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 "";
}
Sample of use:
function checkCookie() {
var clock = getCookie("clock");
if (clock != "") {
//You already have the cookie. Make use of it
} else {
//You still dont have the cookie, create new clock, and save cookie
//i.e.
setCookie("clock", new Date().getTime().toString(), 365);
}
}

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
}
});

How to clear session when reopen the closest tab in a browser

I can invalidate session when i close the tab or windows of browser, but when i click to reopen the closest tab it loads me the recent page as it is.
I want to redirect to login page if the reopen is clicked, I clear the cookies onUnbeforeUnload but it doesn't work.
here is my code:
`$(window).on("beforeunload", function(e) {
var aCookies=document.cookie.split('; ');
for (var i = 0; i < aCookies.length; i++) {
var cookie = aCookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + '=0; expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/';
}
window.location.href = "/safe-unsecured/logout";`
}
and on load of the page i clear cookies;
Any help would be appreciated
browsers will not load a new page on closing or browsing away from a page. That logout page will never be requested.
Also, as long as the browser is not restarted, the session will exist in the browser. A session is not invalidated by a tab closing, but by the entire browser closing. The only way to really achieve what you want is having your cookies live for one minute and have a timer running that updates the cookie expiry every 10 seconds so it doesn't expire as long as the page is open, or the tab isn't re-opened within a minute.
This is an example of the update code. You'll need to add logic yourself that checks for the existance of the cookie and everything else you need for validation.
window.myCookieValueThatIReadBefore = 'Hello';
window.setInterval(function() {
setCookie('cookie_name', window.myCookieValueThatIReadBefore,1)
}, 1000*10);
function setCookie(cname, cvalue, exminutes) {
var d = new Date();
d.setTime(d.getTime() + (60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

I am trying to create popup div for one time load on whole website

This is popup-up div and it's working good. But it's load every time after I refresh the browser and what I want? I need this only one time when user open my website.
Any idea how to control this. FYI this is magento-2 popup.
require(
[
'jquery',
'Magento_Ui/js/modal/modal'
],
function(
$,
modal
) {
var options = {
type: 'popup',
responsive: true,
innerScroll: true,
//title: 'popup modal title',
buttons: [{
text: $.mage.__('Continue'),
class: '',
click: function() {
this.closeModal();
}
}]
};
var popup = modal(options, $('#popup-modal'));
$('#popup-modal').modal('openModal');
}
);
$(document).ready(function() {
$(".actions").click(function() {
alert("The paragraph was clicked.");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="popup-modal">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<h1>Subscribe for Our <span>exclusive offer</span></h1>
<p>Be the first to know about new arrivals exclusive offers and promotions</p>
<?php echo $block->getLayout()->createBlock('Magento\Newsletter\Block\Subscribe')->setTemplate('subscribe.phtml')->toHtml();?>
</div>
Since normal JavaScript (actually NodeJS works server side) only handles client side operations (i.e. your browser), it cannot "remember" that a pop-up was shown once after a page reload. JavaScript need some kind of help for it. The point is that you do not need to care about the JavaScript part that much, but more about PHP in this case.
1.: You could save this information in a cookie, which could save the information if a pop-up was shown once. Only downside is that when you clear your browser cookies, the pop-up would come up again.
2.: You could you the MySQL Database to store this information permanently. Therefore you would need your own custom module though. Good examples can be found in the search.
My recommendation is to create your own module if you haven't already and extend the database table for customers with your information.
Hope this helps you to get in the right direction.
Add cookie there are some functions related to CREATE ,READ and REMOVE cookie please find this fiddle or below snippet for more information.
I hope it'll help you
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
var expires = "; expires=" + date.toUTCString();
}
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);
}
$(function(){
if(readCookie('OnlyONCE') == null)
{
$('#popup-modal').modal('openModal');
createCookie('OnlyONCE','true',7);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cookie" style="display:none;">POP UP
<a href="#" class="cookie-close">
<span class="icon" onclick='onClose()'>X</span>
</a>
</div>

Third party cookie to check if the browser block it by default

I want to check which browser blocks by default third party cookie.
I though to create a local file .html with a third party cookie and open it to every browser to check it will open. Is this a good option?
I plan to use this example but is it a third party cookie?
<!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) == 0) {
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>
This code will create a 1st party cookie - i.e. the domain of this cookie will match the domain of the page loaded.
In order to create a third party cookie you must request a resource from a different domain than the page that requests that resource. This resource could set a cookie using either javascript or HTTP header command (which is initiated by server side code like PHP).
If you are just doing your own survey to gain information about which browsers accept 3rd party cookies by default then it may be worthwhile looking at the specification for each browser to see what the official line is before going to the effort of testing.

Categories

Resources