0

I have a toggle switch that shows and hides an email address that I want to be consistent on each page of my website.

Here's the code I'm using now for the toggle effect, which is working great. (Don't worry, I'm using email obfuscation techniques on my actual site, I've just simplified the code below for the sake of tidiness).

HTML

<a id="contact-switch" href="javascript:void(0);">Contact</a>
<div id="contact-content">xxx@gmail.com</div>

jQuery

<script type="text/javascript">
    $("#contact-switch").click(function() {
    $("#contact-content").fadeToggle("fast", "linear");
  });
</script>

What would be the best way to keep the state of this toggle consistent on each page of my site assuming I have these same elements on each page of my site?

In other words if I have the email address showing on one page, the toggle will be activated on the next page I go to, and if I turn it off on the next page then it will stay turned off on the next page after that, etc?

I've heard something about storing info in window.load but I'm not sure what that means. Any help would be greatly appreciated. Thank you!!

Danny Cooper
  • 355
  • 1
  • 8
  • 25

3 Answers3

2

You need a way to pass data to a different page. In this case I think you best use cookies: How do I set/unset cookie with jQuery?

Community
  • 1
  • 1
sroes
  • 14,663
  • 1
  • 53
  • 72
  • Thank you, I now understand how to set a cookie with the jQuery plugin, but how can I add it into the toggle script I have above so that clicking my switch changes the value of the cookie back and forth with each click of the switch? – Danny Cooper Oct 21 '12 at 09:13
1

you need a persitent storage to keep a flag for your toggle state. This could be your database, cookies, session vars ... etc. You can try using window.localStorage or window.sessionStorage some other techniques, but normally they arn't supported in old browsers .

Reflective
  • 3,854
  • 1
  • 13
  • 25
  • Would using the jQuery cookie plugin be the easiest and simplest method since I'm already using jQuery? I know how to use PHP and MySQL databases to store variables but that seems cumbersome for such a simple application as this. – Danny Cooper Oct 21 '12 at 08:55
  • 1
    if it is a simple app, just use sessions as you mention ... or window.localStorage if the app will be used just with 'modern' browsers – Reflective Oct 21 '12 at 08:57
  • Got it, that seems the simplest but I want to cover my bases so I think I'm going to go with using jQuery cookies if I can figure out how to get them to toggle. – Danny Cooper Oct 21 '12 at 09:14
0

I'd recommend that you take a look at PersistJS - it leverages newer web technologies to persist data across requests (but gracefully falls back to cookies if it needs to.)

alexpls
  • 1,914
  • 20
  • 29