Set cookie in MTurk HIT - javascript

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).

Related

How to check if an element has a class using PHP in Wordpress function.php file

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>

Set cookie after closing div [duplicate]

This question already has answers here:
How do I create and read a value from cookie with javascript?
(23 answers)
Closed 5 years ago.
Here is my html:
<span class="boxclose" id='close'>X</span>
Here is my script:
<script type="text/javascript">
window.onload = function(){
document.getElementById('close').onclick = function(){
this.parentNode.parentNode.parentNode
.removeChild(this.parentNode.parentNode);
return false;
};
};
</script>
All works, but i have no idea how i would update the script to set a cookie to remember, once it has been closed. Any help would be appreciated, thanks
Saving and reading cookies
If you want to read and save cookies the easy way you can use the two functions below from W3Schools. If the close element gets clicked I create a cookie named "closed" for which I set the value to "True". On the page load the cookie "closed" just gets checked if it was indeed already clicked.
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(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=/";
}
window.onload = function() {
if (getCookie("closed") == "True") {
document.getElementById('close').parentNode.parentNode.parentNode.removeChild(document.getElementById('close').parentNode.parentNode);
} else {
document.getElementById('close').onclick = function() {
setCookie("closed", "True", 42);
this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);
return false;
};
}
};
For more information about cookies click here.
Saving inside and reading from the localStorage
This is an example with localStorage which might be interesting for you since a localStorage item is almost like a cookie.
Once you click on the close element I store that it has been clicked inside the localStorage by using localStorage.setItem("closed","True");. To now check if the element was already closed by the visitor on a previous visit etc. you can use localStorage.getitem("closed") which will return "True" (in this case) and compare it to the String "True".
window.onload = function() {
if (typeof(Storage) !== "undefined") {
if (localStorage.getItem("closed") == "True") {
document.getElementById('close').parentNode.parentNode.parentNode.removeChild(document.getElementById('close').parentNode.parentNode);
}
document.getElementById('close').onclick = function() {
this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);
localStorage.setItem("closed", "True");
return false;
};
} else {
alert("Your browser does not support localStorage");
}
};
Click here for a functioning jsfiddle.
For more information about localStorage I recommend W3Schools.

set cookie on page to show bootstrap popup once a day

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

Language switcher - Javascript/jQuery and Cookies

Using both internet and Stack Overflow resources I managed to write a crude HTML website, that allows the user to switch Language of it on the fly, using Javascript, jQuery and XML.
Now, the problem I ran into is to keep the preferred language across the entire portal, without the need to change it each time when navigating through it. I have decided to use a simple cookie to keep the track of it, but it seems I have messed something up, and I can't figure out what I'm doing wrong.
Basically speaking, the page itself has text in the code itself (as a backup just in case), however the text becomes invisible when booting the site, until I switch a language, nor the language is kept when I navigate the portal. For the former, I assumed that the script was reading some empty or overall wrong cookie, so I made an attempt to filter it out and use a default language, but in vain. As for the latter issue, I guess I save the cookie itself wrong as well, but I can't seem to figure out what's wrong with it.
Any help/advice would be appreciated.
function changeLanguage(lang) {
$(function() {
$.ajax({
url: 'jezyki.xml',
success: function(xml) {
$(xml).find('translation').each(function(){
var id = $(this).attr('id');
var text = $(this).find(lang).text();
$("." + id).html(text);
if (lang === "") { }
else {
var title = lang;
createCookie("language", title, 365);
}
});
}
});
});
}
$(document).ready(function () {
$("input[name='radio-language']").click(function () {
changeLanguage($(this).val());
});
});
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 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;
}
window.onload = function (e) {
var cookie = readCookie("language");
var domyslny = "english";
if (title === "") { changeLanguage(domyslny); } else { changeLanguage(title); }
}
Apologies if this is something silly, I am quite a newbie when it comes to Javascript/jQuery.

Cookie jquery hide and show div

I wanna use my javascript cookie to let the application see if the user already loggedIn.. i get the value of the cookie in my console.. but whenever i make an statement and wanna hide a div the div doesn't do anything it doesn't show or hide.. can you guys please help me??
function writeCookie(name,value,days) {
var date, expires;
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires=" + date.toGMTString();
}else{
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var i, c, ca, nameEQ = name + "=";
ca = document.cookie.split(';');
for(i=0;i < ca.length;i++) {
c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(nameEQ) == 0) {
return c.substring(name.length,c.length);
}
}
return '';
}
var user = readCookie('email');
if (!user) {
document.getElementById('loginNav').style.display = 'block';
document.getElementById('username').style.display = 'block';
$("#loginNav").css("display","block");
}else{
$("#loginNav").css("display","block");
console.log( $("#loginNav").css("display","block"));
}
if $('#loginNav').length == 0 then your element has not been loaded yet.
Ensure that this code comes after your jquery link and it is surrounded by a :
$(document).ready(function(){
var user = readCookie('email');
if (!user) {
$('#loginNav, #username').show();
}else{
$("#loginNav, #username").hide();
//did you forget to hide the username?
}
});
Make sure you load all your JS files at the end of your HTML age.
Hi set the "display" property to "none" to hide.... and "block" to show
I would also use "visibility":
if (!user) {
$("#loginNav, #username").css("display","block");
$("#username, #username").css("visibility","visible");
}else{
$("#loginNav, #username").css("display","none");
$("#username, #username").css("visibility","hidden");
}

Categories

Resources