I'm writing a simple diary application and I'd like the user to input the entry on one page and have some js script take that entry and collect it into a different page ("diary-posts"). With the code below I can only collect posts within the same page however:
<! DOCTYPE html>
<html lang="en">
<body>
<header class="text-center">
<h2>
Diary Posts
</h2>
</header>
<div class="wrapper text-center">
<textarea id="txt" rows="3" placeholder="How's your day?"></textarea>
<div class="text-l">
<button onclick="getRs()">Create</button>
</div>
<div id="rs" class="wrapper"></div>
<script src="diary-script.js"></script>
</body>
</html>
function _(id){
return document.getElementById(id)
}
function getRs() {
let txt = _('txt').value
const d = new Date()
_('rs').innerHTML += `<div class="card"><p>${txt}</p>
<small>${d.toLocaleTimeString()}, ${d.toLocaleDateString()}</small></div>`
}
How can I modify this in a simple way to achieve what I want?
There is a lot of ways but I recommend you these options. Choose the best one that works for you.
1. Cookie
This option is best if you want it to use in backend too, because you send cookies data to the backend by every requests. so the data must NOT be too large and must be needed in the backend. otherwise you should use the "localStorage".
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 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 "";
}
setCookie("name", value, 1) //set the cookie for 1 day
getCookie("name") //get the cookie everywhere you want
2. localStorage
If you want to use it only in the user device, this is the option you wanna pick.
note: localStorage stores the data with no expiration date. the data will never ever will be deleted automatically unless you delete it or the user delete it by browser settings.
localStorage.setItem("fieldName", data); //set the item
localStorage.getItem("fieldName"); //get the item
3. sessionStorage (recommended)
sessionStorage is similar to localStorage but the difference is that this will be deleted when user close the browser. so if the data is not so much important and you don't need it next time the user visits the page, this option is made for you.
sessionStorage.setItem("fieldName", data); //set the data
sessionStorage.getItem("fieldName"); // get the data
4. Use backend
you can also store the data in database via backend. you can use an API to send the data to the backend. this option is good for when you need the data in backend and you always need it.
I am looking for a solution for my age check to display every time a user enters the site. Currently it is set to display once a day for a user. If they leave the site and comes back that day I need it display again. It is on Shopify.
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();
};
Rather than setting it to expire in one day, set it to expire after 0 seconds.
I need to show the tipical 'use of cookies' message at the bottom of the page just when some user visits the web, and just show it once at day,I'm trying but my code it's not working properly. here's the code I have so far...
<div id="cookie1"> </div>
<button id="botoncookie">Acept</button>
<script type="text/javascript">
document.getElementById('cookie1').style.bottom = '-50px';
var expiresdate = 5000 ; //1 day
$('#botoncookie').on('click',function(){
var mensaje = document.cookie.split('cookie1=')[1] + expiresdate;
$('#botoncookie').hide();
$('#cookie1').hide();
});
if(mensaje != null){
document.getElementById('cookie1').style.display = 'none';
}else{
document.cookie = 'cookie1=visto;path=/';
}
</script>
Set a cookie with an expiration time of 24*60*60 and whenever a page is loaded, check if the cookie exists, otherwise, display the message.
When your page loads execute the following function. This will check when the cookieMsg was displayed. If already displayed today, no need to display. As a boundary case, for the first time load, it will be null and it will anyway works.
EDIT: In the previous snippet i was just comparing the date which included time as well, you need to specifically check for date only.
function displayMsg(){
var today = new Date();
var lastDisplayedOn = localStorage.getItem('cookieLastDisplayed');
if(lastDisplayedOn){
var ld = new Date(lastDisplayedOn)
if(today.getDate() == ld.getDate() && today.getMonth() == ld.getMonth() && today.getFullYear() == ld.getFullYear()){
donotDisplay()
}else{
displayCookie()
}
}else{
displayCookie()
}
}
General information: I'm trying to create a popup modal window to verify customer zip codes - the website is only for people within a particular range of codes, so I just need it to pop up, take their input, and if they're eligible to shop, close, let them shop, and not show up again at least for the session, and if they aren't eligible, to redirect them to another website.
I have it working perfectly in Firefox, Edge, and IE, but Chrome, while running most of it just fine, completely ignores other parts. This is my first real attempt at doing anything with Javascript, so I'm hoping it's a simple answer.
Another note: sorry about all the commented out lines, I've been trying to keep close track of where I've been so I can undo my changes more easily if necessary.
HTML:
<!--START: ZipCheckModal-->
<!-- Trigger/Open The Modal -->
<!--<button id="myBtn">Open Modal</button>-->
<!-- The Modal -->
<div id="zipModal" class="zipmodal">
<!-- Modal content -->
<div class="zipmodal-content">
<div class="zipmodal-header">
<span class="close">×</span>
<h2>Welcome to Nature's Warehouse Ohio!</h2>
</div>
<div class="zipmodal-body">
<div class="overblur">
<div class="zipcheckarea" id="zipcheckarea"><h1>Check your zip code</h1><br /><p>This site is for customers within our Ohio Local Delivery Zone. Check to see if you're eligible!</p><br />
<form class="zipbox">
<input type="number" id="custzip" placeholder="Your Zip" maxlength="5"/><br />
<input type="submit" id="zipbtn" value="Check Zip" onclick="checkZip()" /><br />
</form></div></div>
</div>
Some Javascript that is inline, immediately beneath the above (at some point I couldn't get it to run in a separate file, so I just left it inline)
// Get the modal
var zipmodal = document.getElementById('zipModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the window opens, open the modal
//Add "if there is no cookie" here
checkZipCookie();
//window.onload = function() {
// zipmodal.style.display = "block";
//}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
zipmodal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
//window.onclick = function(event) {
// if (event.target == zipmodal) {
// zipmodal.style.display = "none";
// }
//}
And finally, the separate Javascript file:
function checkZip() {
var custzip = document.getElementById("custzip").value;
var ziparray = ["44606", "43803", "43804", "44608", "44610", "44611", "43805", "44612", "44613", "44617", "44618", "44622", "44624", "44627", "43824", "44628", "44633", "43828", "44636", "44637", "44638", "44647", "44654", "44659", "44660", "44661", "44662", "44666", "44667", "44676", "44677", "43840", "44680", "44681", "44687", "44689", "44690", "44691", "44697"];
if (ziparray.indexOf(custzip) > -1) {
document.getElementById("zipcheckarea").innerHTML = "You qualify for same-day delivery!\nIn a moment you will be redirected to the home page.";
document.getElementById("zipcheckarea").className = "delaymsg";
setTimeout(sendOH, 3000);
} else {
document.getElementById("zipcheckarea").innerHTML = "We're sorry, you don't qualify for same-day delivery.\nTry our regular website, where we offer FREE shipping on orders over $24.95!";
document.getElementById("zipcheckarea").className = "delaymsg";
setTimeout(sendNY, 4000);
}
}
function sendOH() {
setZipCookie("resident");
zipmodal.style.display = "none";
//window.location.href = "http://ohio.natureswarehouse.net";
}
function sendNY() {
window.location.href = "http://natureswarehouse.net";
}
function setZipCookie(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;
}
function getZipCookie(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 checkZipCookie() {
var isCookie = getZipCookie("resident");
if (isCookie != "") {
//Show nothing, free to browse
} else {
//Run the modal window
window.onload = function() {
zipmodal.style.display="block";
}
}
}
The problems I'm seeing are 1) Chrome doesn't follow the correct close modal/redirect, it just closes the modal window no matter what the input is, 2) ignores the timeouts before redirecting, and 3) doesn't set the cookie, so the modal keeps popping up every time. I get the same issues messing with it in codepen (but only in Chrome), and it seems to run flawlessly in the other browsers.
I'm not getting any errors in my console or anything, Chrome seems to think it's doing everything right. If you want to check out the actual model, it's at ####.
It's really strange that other browsers behave as You suspect.
The reason for redirect is a form submission, which is caused by a click on an input of type "submit".
You probably would like to prevent the form from submitting:
document.querySelector('form.zipbox').onsubmit = function (e) { e.preventDefault(); };
I'm working on a page that refreshes itself every 5 minutes
<meta http-equiv="refresh" content="1200;url=?meta_refresh=true" />
On the page is a JS script that should run the first two times the page reloads. When the page reload's for the third time, the script should not execute.
So far, I've created a cookie and given it an initial value of 0, for every refresh I increment it's value (rewrite the cookie) and if the value is smaller than 3 i execute the part of a script. The things is that if I close the tab and reopen the page in another tab, the cookie has the incremented value, and I want it to always start from 0.
Here's what i've done so far:
var value = 0;
$(document).ready(function() {
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 cookieValue = getCookie('siteRefreshCookie');
if (cookieValue !== '') {
var newValue = parseInt(getCookie('siteRefreshCookie')) + 1;
if (newValue < 3) {
//script to be executed
document.cookie = "siteRefreshCookie="+ newValue +";";
}
} else {
document.cookie = "siteRefreshCookie="+ value +";";
}
}
checkCookie();
})
Could I suggest using a query string instead?
<meta http-equiv="refresh" content="1200;url=?meta_refresh=true&count=1" />
Then as an ASP programmer myself I would do something like:
<meta http-equiv="refresh" content="1200;url=?meta_refresh=true&count=<%=CInt(0 & Request.Querystring("count")) + 1%>" />
But you can probably achieve this using PHP, or even JS I imagine if you have no back-end language suitable.
The problem with using cookies is that they are tied to that website, rather than that window. Even if you reset the cookie with an unload function like Pete suggested, you'll then run into problems like if for example you have two tabs open with the same page.