Cleaning up js file [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
I'm working on a project that I set functions to create a cookie based off of a form value. That cookie then populates another form's input values. At first, I only needed to set three cookies, so this wasn't overly big (calling the functions)... the requirements changed, and I went from needing three cookies to now needing eight, so my function calls are getting a little out of hand. Is there a more efficient way of doing this?
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=/";
}
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(c, el) {
var user = getCookie(c);
if (user != "") {
document.getElementById(el).value = user;
document.getElementById(el).setAttribute("value", user);
document.getElementById(el).setAttribute("readonly", "readonly");
}
}
function setEmployee(e, field) {
var emp = getCookie(e);
if (emp != "") {
document.getElementsByClassName(field).value = emp;
var perm = document.getElementsByClassName(field);
perm[0].setAttribute("value", emp);
}
}
$(document).ready(function(){
var firstName = "firstName";
var lastName = "lastName";
var phoneCookie = "phone";
var emailCookie = "email";
var companyCookie = "company";
var addressCookie = "address";
var stateCookie = "state";
var zipCookie = "zip";
$('#form').submit(function(){
var first = $('#FirstName').val();
var last = $('#LastName').val();
var phone = $('#Phone').val();
var email = $('#Email').val();
var company = $('#Company').val();
var address = $('#Address').val();
var state = $('#State').val();
var zip = $('#PostalCode').val();
setCookie(firstName, first, 10);
setCookie(lastName, last, 10);
setCookie(phoneCookie, phone, 10);
setCookie(emailCookie, email, 10);
setCookie(companyCookie, company, 10);
setCookie(addressCookie, address, 10);
setCookie(stateCookie, state, 10);
setCookie(zipCookie, zip, 10);
});
if($('#census').is(':visible')){
checkCookie(firstName, "contactName");
checkCookie(lastName, "contactLast");
checkCookie(phoneCookie, "contactPhone");
checkCookie(emailCookie, "contactEmail");
checkCookie(companyCookie, "contactCompany");
checkCookie(addressCookie, "contactAddress");
checkCookie(stateCookie, "contactState");
checkCookie(zipCookie, "contactZip");
}
});

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 in MTurk HIT

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

Javascript - Popup every time customer enters the store

I saw the age-verification snippet solution for my problem and it worked great. But in that solution the occurrence of that popup is based on the number of days. I want the popup to occur every time the user enters my website. How to do it?
Here's is the JS part of the snippet code.
<script>
function ageCheck() {
var min_age = {{ age }}; // Set the minimum age.
var year = parseInt(document.getElementById('byear').value);
var month = parseInt(document.getElementById('bmonth').value);
var day = parseInt(document.getElementById('bday').value);
var theirDate = new Date((year + min_age), month, day);
var today = new Date;
if ((today.getTime() - theirDate.getTime()) < 0) {
window.location = 'http://google.com'; //enter domain url where you would like the underaged visitor to be sent to.
} else {
var days = 1; //number of days until they must go through the age checker again.
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
document.cookie = 'isAnAdult=true;'+expires+"; path=/";
location.reload();
};
};
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;
};
var isAnAdult = readCookie('isAnAdult');
if (isAnAdult) {
document.write("<style> #prompt-background { display: none; }</style>");
};
</script>
and the button that function is called on
<button id="submit_birthdate" class="exitbutton" onclick="ageCheck()">Enter</button>
How to modify this code so that the popup appears every time?

Firebase Failed to Increment Counter

I have two firebase scripts; one of them is working fine but other not. I don't have any idea what is going on. Those two scripts are based on same logic. Only difference is that counter 2 data is always incremented irrespective of website home page or post page while counter 1 data is incremented only it is post page (i.e. pathname!='/'). Fortunately counter 1 is working fine but counter 2 not. I don't have any idea what i'm doing wrong..
Please help me to get rid of this bug. Any kind of help would be appreciated.
$(function(){
var parentDataRef = 'https://blablabla.firebaseio.com/';
//counter 1
var postRef = new Firebase(parentDataRef+'one');
getFirebaseData(postRef,'post',function(pData){
alert(pData);
});
//counter 2
var blogRef = new Firebase(parentDataRef+'two');
getFirebaseData(blogRef,'blog',function(bData){
alert(bData);
});
});
//get Firebase data
function getFirebaseData(r,bp,back){ //Reference, Blog or Post, Return data
var doctitle = document.title;
r.once('value', function(e) {
var data=e.val();
if (data==null){data=1;}
else if (getCookie(doctitle)!='yes'){
if (bp=='post' && window.location.pathname!='/') {data++;}
else if (bp=='blog') {data++;}
}
r.set(data);
back(data);
setCookie(doctitle,'yes',7);
});
}
//set Cookie Data
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+'; path=/';
}
//get Cookie Data
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 '';
}
Can I suggest to use transactions your counters ?
var upvotesRef = new Firebase('https://docs-examples.firebaseio.com/android/saving-data/fireblog/posts/-JRHTHaIs-jNPLXOQivY/upvotes');
upvotesRef.transaction(function (current_value) {
return (current_value || 0) + 1;
});

Cookie value to define style on page load

I am using the scripts from here http://www.quirksmode.org/js/cookies.html and have successfully created a cookie.. it is set based on the users response to the age drop down. However I am having trouble doing anything with it. I would like to have a style defined if a cookie is present. Here is the bulk of my scripts..
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 checkAge(){
var min_age = 13;
var year = parseInt(document.forms["emailForm"]["year"].value);
var month = parseInt(document.forms["emailForm"]["month"].value) - 1;
var day = parseInt(document.forms["emailForm"]["day"].value);
var theirDate = new Date((year + min_age), month, day);
var today = new Date;
if ( (today.getTime() - theirDate.getTime()) < 0) {
var el = document.getElementById('emailBox');
if(el){
el.className += el.className ? ' youngOne' : 'youngOne';
}
document.getElementById('emailBox').innerHTML = "<style type=\"text/css\">.formError {display:none}</style><p>Good Bye</p><p>You must be 13 years of age to sign up.</p>";
createCookie('age','not13',0)
return false;
}
else {
createCookie('age','over13',0)
return true;
};
};
window.onload=function(){
var x = readCookie('not13');
if (x) {
document.getElementById('emailBox').innerHTML = "<style type=\"text/css\">.formError {display:none}</style><p>Good Bye</p><p>You must be 13 years of age to sign up.</p>";
}
}
Age verification works and cookie is set.... no errors (from Firebug).. can anyone see what I am doing wrong?
with jQuery would be something like this
if (x) {
var style = "<style type=\"text/css\">.form {display:none}</style>";
$("header").append(style);
}
Looking at your code it should work. There's nothing incorrect about it.
The only thing I would suggest is that instead of injecting a style tag into a empty div, inject a link tag into the head. This will mean that your css changes and maintainance won't need to touch the js code.
I got it.. I was looking for the cookie value and needed to look for the name and then create an if statement based on the value. so..
var x = readCookie('age');
if (x=='not13') {
document.getElementById('emailBox').innerHTML = "<style type=\"text/css\">.formError {display:none}</style><p>Good Bye</p><p>You must be 13 years of age to sign up.</p>";
}

Categories

Resources