const cookieButton = document.getElementById('store-cookie')
cookieButton.addEventListener('click', e => {
const input = document.getElementById('fav-cookie').value
let date = new Date()
let minutes = 30;
date.setTime(date.getTime() (minutes * 60 * 1000))
document.cookie = `favCookie=${input}; expires=${date.toTimeString()};`
})
I'm working on a coding problem meant to be only used in javaScript that is asking to make a cookie with the value of an input field (on a linked html) when pressing a button. The bonus for this question is making the cookie expire after 30min when it's created. Currently this code will just save the favCookie=input; but it won't add an expiration date. Any help would be really appreciated!
CodePudding user response:
You could create 2 date variables, on the second use the setMinutes method to add 30mins to the current time then create a function to clear/change the value if and when the current date/time equals the new date.
var expire = new Date();
expire.setMinutes( expire.getMinutes() 30 );
CodePudding user response:
Use toUTCString()
instead.
const cookieButton = document.getElementById('store-cookie');
cookieButton.addEventListener('click', e => {
const input = document.getElementById('fav-cookie').value;
const date = new Date();
date.setTime(date.getTime() (30* 60 * 1000));
document.cookie = `favCookie=${input}; expires=${date.toUTCString()};`;
});
Cookies are always tricky. I believe it is because your timestamp should be formatted like so:
2021-10-23T20:32:38.000Z
Instead you currently have set by toTimeString()
22:29:12 GMT 0200 (Central European Summer Time)