We help IT Professionals succeed at work.

Why do I love all of my javascript changes once a form is submitted on my webpage?

shampouya
shampouya asked
on
My webpage below has a changeable background color, but once the form is submitted or once the page is reloaded, it goes back to the default color. Is there a simple way to prevent that in javascript?

my webpage
Comment
Watch Question

HonorGodSoftware Engineer
CERTIFIED EXPERT

Commented:
I presume that when you say "love", you mean "save" ;-)

Commented:
You may save your background color into cookie and load them when the page is loaded.

Author

Commented:
Sorry I meant to say why do I lose all my javascript changes. Is there any way to keep the changes once the form on my page is submitted? Does the form being submitted count as a reload of the page?
Commented:
For example:

Add these functions to your script:

function saveTheme(theme)
{
    setCookie('theme', theme);
}

function loadTheme()
{
    theme = getCookie('theme');
    if (theme == 'purple') { purpleTheme(); }
    else { if (theme == 'blue') { blueTheme(); }
    else { if (theme == 'red') { redTheme(); } }
    }
}

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

Open in new window


and have some mods to your html

<li><img src="purpleSquare.jpg" onClick="purpleTheme();saveTheme('purple');" id="purpleSquare"></li>
<li><img src="blueSquare.jpg" onClick="blueTheme();saveTheme('blue');" id="blueSquare"></li>
<li><img src="redSquare.jpg" onClick="redTheme();saveTheme('red');" id="redSquare"></li>

Open in new window


and also put this to your script file
$(function(){
    loadTheme();
});

Open in new window

Author

Commented:
thanks

Explore More ContentExplore courses, solutions, and other research materials related to this topic.