Hi,
I have html like this:
<div id="inputarea" style="color:black;font-size:15px;">
I want to store the style data into a cookie so I did this:
setCookie('savedstyle',inputarea.style);
So in my next session inputarea should load the data from that cookie and set it as the style for the inputarea like this:
if(getCookie('savedstyle')) {
inputarea.style = getCookie('savedstyle');
}
nothing happens because the value stored in the cookie looks something like this: [object CSS properties]. Why is that? How can I store the value properly?
Thank you.
CodePudding user response:
The .style in JS just stores setters for CSS attributes. It's not useful for reading information.
If you just want to store the inline style use:
setCookie('savedstyle', inputarea.getAttribute('style'))
and to retrieve
inputarea.setAttribute('style', getCookie('savedstyle'))
CodePudding user response:
Try these. These are some boilerplate functions I use for my projects when I need it.
readCookie = (cname) =>
{
let name = cname '=';
let decodedCookie = decodeURIComponent(window.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 '';
}
createCookie=(cname, cvalue)=>
{
let d = new Date();
d.setTime(d.getTime() (10*24*60*60*1000));
let expires = 'expires=' d.toUTCString();
window.document.cookie = cname '=' cvalue ';' expires ';path=/';
}
deleteCookie = (name) =>
{
if(readCookie(name))
{
window.document.cookie = name '=;path=/;expires=Thu, 01 Jan 1970 00:00:01 GMT';
}
}
The readCookie function reads a cookie by the name. createCookie you give it a name and a value, and the deleteCookie deletes a cookie by name. Pretty self explanatory :D.
