I am new to JS so any help would be appreciated.
I have created an XML request upon the page loading a video to check for cookies, and then replace a div element "tmx" with an external HTML file from my website. However the page keeps on reloading after fetching the XML request after injecting it to "#tmx".
Another thing that I noticed is when I press accept tnc button on my document without the checkbox being ticked, the whole page is being completely reloaded.
I think it might be the return value that might be wrong.
function setCookie(cname, cvalue, exdays) {
if(document.getElementById('agree').checked){
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let 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 "";
}
function checkCookieOnLoad() {
if(getCookie("clicklink") === "yes") {
var elem = document.getElementById("tmx");
elem.parentNode.removeChild(elem);
// var elem2 = document.getElementById("ooo");
// elem2.parentNode.removeChild(elem2);
var video = document.createElement('video');
video.type = "video/mp4";
video.src = ".//vid1.mp4";
video.autoplay = true;
video.muted = true;
video.id = "vdd1"
document.body.appendChild(video);
video.addEventListener("timeupdate", function(){
// current time is given in seconds
if(this.currentTime >= 4.8) {
// pause the playback
this.pause();
this.remove();
location.replace("https://www.test.com/index.html");
}
});
return true;
} else {
const xhr = new XMLHttpRequest();
const contianer = document.getElementById('tmx');
xhr.onload = function() {
if (this.status ===200){
contianer.innerHTML = xhr.responseText;
}
}
xhr.open('get', 'tnc.html');
xhr.send();
}
}
setTimeout(function() {
function setCookie(cname, cvalue, exdays) {
if (document.getElementById('agree').checked) {
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let 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 "";
}
function checkCookieOnLoad() {
if (getCookie("clicklink") === "yes") {
var elem = document.getElementById("tmx");
elem.parentNode.removeChild(elem);
// var elem2 = document.getElementById("ooo");
// elem2.parentNode.removeChild(elem2);
var video = document.createElement('video');
video.type = "video/mp4";
video.src = ".//vid1.mp4";
video.autoplay = true;
video.muted = true;
video.id = "vdd1"
document.body.appendChild(video);
video.addEventListener("timeupdate", function() {
// current time is given in seconds
if (this.currentTime >= 4.8) {
// pause the playback
this.pause();
this.remove();
location.replace("https://www.test.com/index.html");
}
});
return true;
} else {
const xhr = new XMLHttpRequest();
const contianer = document.getElementById('tmx');
xhr.onload = function() {
if (this.status === 200) {
contianer.innerHTML = xhr.responseText;
}
}
xhr.open('get', 'tnc.html');
xhr.send();
}
}
}, 5000);
/*This code will run after 5 seconds after the loading of HTML CSS and your JS files. Try it. Hope it helps you!!*/
Related
I am trying to hide an element on the front-end and remember the user choice by creating a cookie in PHP.
Here is how I have it set up:
I have some HTML and JS scripts inside an HTML widget on the page on the front-end
<div id="training-banner"> training banner design here </div>
<button onclick="myFunction()" id="close-btn">X</button>
<script>
function myFunction() {
var element = document.getElementById("training-alert");
element.classList.add("hidebanner");
}
</script>
Then I have written the cookie function inside the function.php of the child theme:
add_action('init', function() {
if (!isset($_COOKIE['training_banner_cookie'])) {
setcookie('training_banner_cookie', 'showbanner', strtotime('+1 day'));
}
if (class_exists('hidebanner')){
?><style>#training-alert{display:none;}</style> <?php
setcookie('training_banner_cookie', 'hidebanner', strtotime('+1 day'));
}
$cookieValue = $_COOKIE['training_banner_cookie'];
if ($cookieValue == "hidebanner"){
?><style>#training-alert{display:none;}</style> <?php
}
});
For some reason, the class_exists() PHP function does not work, any idea how this can be achieved?
https://www.php.net/manual/en/function.class-exists.php
class-exists is not used in your case. It is used to check if a Class exists in your PHP code block.
if (class_exists('MyClass')) {
$myclass = new MyClass();
}
What you want to do is to save the choice of the users' choice. You can simply use JS to achieve it.
<div id="training-banner"> training banner design here </div>
<button onclick="myFunction()" id="close-btn">X</button>
<script>
function getCookie(cookieName: string, cookie?: string): string {
const name = cookieName + '='
const decodedCookie = decodeURIComponent(cookie || document.cookie)
const ca = decodedCookie.split(';')
for (let i = 0; i < ca.length; i++) {
let 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(
cookieName,
value,
days,
isSecure = true
): void {
let expires = ''
const secure = isSecure ? '; Secure' : ''
if (days) {
const date = new Date()
date.setTime(date.getTime() + days * 86400000)
expires = ' ;expires=' + date.toUTCString()
}
document.cookie = cookieName + '=' + value + expires + ' ;path=/' + secure
}
function myFunction() {
var element = document.getElementById("training-alert");
element.classList.add("hidebanner");
setCookie('training_banner_cookie_hide', true, 1)
}
function init(){
var shouldHideBanner = getCookie('training_banner_cookie_hide')
if(shouldHideBanner){
var element = document.getElementById("training-alert");
element.style.display = 'none';
}
}
init()
</script>
With the help of #WillyLi's answer, I was able to organize my thoughts and modify his code a bit here is what worked for me:
I modified the getCookie function declaration and simplified it to one parameter cname.
Then I also modified the setCookie and standardized it according to w3school
Finally, I wanted the banner to be hidden immediately as the user clicks the button so I added element.style.display = 'none'; to myFunction()
Here is what the final version looks like:
<button onclick="myFunction()" id="close-btn">X</button>
<script>
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for(let i = 0; i <ca.length; i++) {
let 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(cname, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
let expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function myFunction() {
var element = document.getElementById("training-alert");
element.style.display = 'none';
setCookie('training_banner_cookie_hide', true, 1);
}
function init(){
var shouldHideBanner = getCookie('training_banner_cookie_hide');
if(shouldHideBanner){
var element = document.getElementById("training-alert");
element.style.display = 'none';
}
}
init()
</script>
I recently had issues using javascript cookies inside an MTurk HIT. In particular I'm trying to track user preferences w.r.t showing/hiding the HIT instruction.
My approach so far is the following:
<body>
<div id='instructionButton'>
<!-- Button triggering instruction body to collapse/show -->
</div>
<div id='instructionBody'>
<!-- Instruction content (collapsible) -->
...
</div>
</body>
<script>
const instructionBodyId = 'instructionBody';
const instructionButtonId = 'instructionButton';
const cookieName = 'my_cookie_name';
var isInstructionShown = true;
var instrContent = $('#' + instructionBodyId);
var instrButton = $('#' + instructionButtonId);
function setCookie(name, value) {
var date = new Date();
<!-- Cookie valid for 48h -->
date.setTime(date.getTime() + (48 * 60 * 60 * 1000));
var expires = "; expires=" + date.toUTCString();
document.cookie = name + "=" + value + expires + "; path=/";
}
function getCookie(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 toggleInstructions(isShow) {
setCookie(cookieName, isShow);
isInstructionShown = isShow;
if (isShow) {
instrContent.slideDown();
} else {
instrContent.slideUp();
}
}
function prepare_cookie() {
instrButton.click(function() {
toggleInstructions(!isInstructionShown);
});
let cookieVal = getCookie(cookieName);
if (cookieVal == "false") {
toggleInstructions(false);
} else {
toggleInstructions(true);
}
}
$(document).ready(function() {
prepare_cookie();
});
</script>
The code above shows part of the HIT layout I'm creating, and when testing it out while editing the HIT directly in MTurk, the cookie works as expected (it shows up in Google Chrome and works as expected, showing/hiding the instruction automatically).
Unfortunately, when publishing the HIT, the cookie does not seem to be set (it does not appear in the list of cookies shown in Google Chrome).
I have this code for detecting android:
var mobile = (/android/i.test(navigator.userAgent.toLowerCase()));
if (mobile){
alert("Message to android users");
}
...but how do I get that script to also set a cookie so the android user doesn't continue getting the alert (either on reloading the page, returning later to the page, or navigating to other pages which have the alert)?
I also have this, which uses a cookie to avoid a user viewing a "welcome page" they've already seen:
var RedirectURL = "http://www.example.com/real-home-page.html";
var DaysToLive = "365";
var CookieName = "FirstVisit";
function Action() {
location.href = RedirectURL;
}
DaysToLive = parseInt(DaysToLive);
var Value = 'bypass page next time';
function GetCookie() {
var cookiecontent = '';
if(document.cookie.length > 0) {
var cookiename = CookieName + '=';
var cookiebegin = document.cookie.indexOf(cookiename);
var cookieend = 0;
if(cookiebegin > -1) {
cookiebegin += cookiename.length;
cookieend = document.cookie.indexOf(";",cookiebegin);
if(cookieend < cookiebegin) { cookieend = document.cookie.length; }
cookiecontent = document.cookie.substring(cookiebegin,cookieend);
}
}
if(cookiecontent.length > 0) { return true; }
return false;
}
function SetCookie() {
var exp = '';
if(DaysToLive > 0) {
var now = new Date();
then = now.getTime() + (DaysToLive * 24 * 60 * 60 * 1000);
now.setTime(then);
exp = '; expires=' + now.toGMTString();
}
document.cookie = CookieName + '=' + Value + exp;
return true;
}
if(GetCookie() == true) { Action(); }
SetCookie();
Can the second script be adapted and combined into the first to do something like:
function Action() {
don't-open-that-alert-again;
I've googled and found some js cookie scripts, but all over 100K. Prefer something as succinct as the above.
I'm learning JavaScript and I see that this question has been asked many times, but I can't get this to work for me.
What I want to do is, show a bootstrap modal once a day.
What I have so far is:
function setCookie(cookiename, cookievalue, expdays) {
var d = new Date();
d.setTime(d.getTime()+(expdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
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].trim();
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
//I want to check if there is a cookie.
//if I have not set a cookie, I want to show my modal,
//if there is a cookie then return;
//The cookie should expire in one day.
function checkCookie() {
var showed = getCookie("showed");
if (showed != null && showed != "") {
var date = new Date(showed).getDate();
var currentDate = new Date().getDate();
if (currentDate > date) {
return true;
}
return false;
}
return true;
}
Now, if I change the last return true; to return false; my modal does not show up.
The way it is now I see the modal every time.
What am I doing wrong?
How can I fix this?
function setCookie(cookiename, cookievalue, expdays) {
var d = new Date();
d.setTime(d.getTime()+(expdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cookiename + "=" + cookievalue + "; " + expires;
}
function getCookie(cookiename) {
var name = cookiename + "=";
var startPos = document.cookie.indexOf(name);
if(startPos == -1) return null;
startPos+=(name.length);
if(document.cookie.indexOf(";",startPos) == -1){
return document.cookie.substring(startPos,document.cookie.length);
}
else{
return document.cookie.substring(startPos,document.cookie.indexOf(';',startPos));
}
return null;
}
//I want to check if there is a cookie.
//if I have not set a cookie, I want to show my modal,
//if there is a cookie then return;
//The cookie should expire in one day.
function checkCookie() {
var showed = getCookie("showed");
if (showed != null && showed != "") {
var date = new Date(showed).getDate();
var currentDate = new Date().getDate();
if (currentDate > date) {
return true;
}
return false;
}
return true;
}
Also when setting cookie,
use
setCookie('showed',new Date().toGMTString(),1);
because we are using the value of cookie, not the expire time of cookie to check. So the value must be a datestring
How would i pass my current timer's timing into the next page?
Timer code
var expires = new Date();
expires.setSeconds(expires.getSeconds() + 60); // set timer to 60 seconds
var counter = setInterval(timer, 1);
function timer() {
var timeDiff = expires - new Date();
if (timeDiff <= 0) {
clearInterval(counter);
document.getElementById("timer").innerHTML = "00:00";
return;
}
var seconds = new Date(timeDiff).getSeconds();
var milliSeconds = (new Date(timeDiff).getMilliseconds()/10).toFixed(0);
var seconds = seconds < 10 ? "0" + seconds: seconds;
var milliSeconds = milliSeconds < 10 ? "0" + milliSeconds: milliSeconds;
document.getElementById("timer").innerHTML = seconds + ":" + milliSeconds; // watch for spelling
}
I'm using
<h3 style="color: #ff0000; margin: 0; padding: 0; font-size: 100%;font-weight:normal; font-family: robotolight;"> You have <div id="timer"></div> to complete the game!
in my html.
Is there a way to pass div id='timer'> into the next page?
Thanks.
Reloading the page or loading a new page means reloading javascript since it is runs in the context of the current page. There is good way to pass along javascript variables to a new page; it requires some form of data persistence. Cookies and localStorage are two of the most common ways of persisting data client-side.
Client cookies are written to the browser cache and are transparent in HTTP headers. LocalStorage is a newer mechanism but well supported, allowing up to 5MB of browser storage without passing in headers.
In your use case, instead of storing the timer it would probably make sense to store the timestamp when the timer was started. That way it can be recalculated in the next page from this one static start value.
var timerStart;
var expireDate = new Date();
function displayTimer(){
var now = new Date().getTime();
var timerStart = timerStart || cookieTimer();
val timeDiff = now - timerStart;
document.getElementById("timer").innerHTML = timeDiff.toString();
if(timeDiff > expireDate.getTime()) clearInterval(timerInterval);
}
val timerInterval = setInterval(displayTimer, 1);
// Using cookies
function cookieTimer(){
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 setCookie(cname, cvalue, expireDate) {
var d = new Date();
d.setTime(d.getTime() + expireDate.getTime());
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
var timerCookie = getCookie("timer");
if(timerCookie !== "") return new Date(timerCookie).getTime());
else {
setCookie("timer", timerStart, expireDate);
return new Date().getTime();
}
}
// Using localStorage
function localStorageTimer(){
function setLocalStorageObject(key, obj, expireDate){
obj.expires = expireDate.getTime();
localStorage.setItem(key, JSON.stringify(obj));
}
function getLocalStorageObject(key){
val item = localStorage.getItem(key);
if(item) return JSON.parse(item);
else return {};
}
var timerLocal = getLocalStorageObject("timer");
var now = new Date().getTime();
if(timerLocal && timerLocal.startTime && timerLocal.expires > now) return timerLocal.startTime;
else {
setLocalStorageObject("timer", { startTime: now });
return now;
}
}