Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Back Button Causing Issues With Hidden Divs

Posted on 2016-08-25
5
107 Views
Last Modified: 2016-08-31
On the page I have 2 hidden divs (display: none;) on page load. They are revealed with a jquery click function and then the user submits a form. If the browser back button is pressed, the divs are hidden again. I would like to have the divs shown on back button press, but I have no idea how to do this.
ScreenCast.flv
0
Comment
Question by:seeraig
  • 3
  • 2
5 Comments
 
LVL 55

Accepted Solution

by:
Julian Hansen earned 500 total points
ID: 41771375
The reason they are not showing is that once you move off the page the state of the page is lost.

To preserve the state you would need to use a cookie or local storage to save a value that says whether or not the divs have been shown.
HTML
    <div class="hidden-div"> This is invisible on first read</div>
    <div class="hidden-div"> This is invisible on first read</div>
    <a href="#" class="show-divs">Show</a>

Open in new window

jQuery
<script>
$(function() {
  var state = getState();
  if (state) {
    $('body').addClass('has-state');
  }
  
  $('.show-divs').click(function(e) {
    e.preventDefault();
    $('body').addClass('has-state');
    setState();
  });
});
function getState()
{
  var state;
  if (typeof Storage !== 'undefined') { // Localstorage
    state = localStorage.getItem('__state');
  }
  else { // Cookies
    state = getCookie('__state');
  }
  return state;
}

function setState()
{
  if (typeof Storage !== 'undefined') { // Localstorage
    localStorage.setItem('__state', '1');
  }
  else { // Cookies
    document.cookie = "__state=1";
  }
}

function getCookie(cookie) {
  var ret = false;
    var cookies = document.cookie;
  var pattern = cookie +'=(.*?);';
  var regex = new RegExp(pattern);
  var val = cookies.match(regex);
console.log(val);  
  if (val) ret = val[1];
  
    return ret;
}
</script>

Open in new window

Working sample here
0
 
LVL 55

Expert Comment

by:Julian Hansen
ID: 41771450
Updated code to selectively choose cookie / localstorage in sample
CSS
<style type="text/css">
.hidden-div {
  display: none;
}
body.has-state .hidden-div {
  display: block;
}
body.has-state .show-divs {
  display: none;
}
</style>

Open in new window

HTML
    <div>
      <button class="btn btn-danger" id="reset">Reset</button>
      <input type="radio" value="localstorage" id="localstorage" name="storage" checked/> Local Storage <input type="radio" value="cookie" name="storage" id="cookie"/> Cookie
	  <a href="#" class="show-divs btn btn-primary">Show</a>
    </div>
    <div class="hidden-div"> This is invisible on first read</div>
    <div class="hidden-div"> This is invisible on first read</div>

Open in new window

jQuery
<script>
$(function() {
  if (typeof Storage === 'undefined') {
  $('#localstorage').prop({checked: false, disabled: true});
  $('#cookie').prop('checked', true);
  }
  var state = getState();
  if (state) {
    $('body').addClass('has-state');
  }
  
  $('.show-divs').click(function(e) {
    e.preventDefault();
    $('body').addClass('has-state');
    var type = $('input[name="storage"]:checked').val();

    setState(type);
  });
  
  $('#reset').click(function(){
  if (typeof Storage !== 'undefined') {
    localStorage.clear();
  }
  document.cookie = "__state=; expires=0";
  location.reload();
  });
});
function getState()
{
  var state = false;
  if (typeof Storage !== 'undefined') { // Localstorage
    state = localStorage.getItem('__state');
  }
  
  if (!state) {
    state = getCookie('__state');
  }
  
  return state;
}

function setState(type)
{
  if (type == 'localstorage' && typeof Storage !== 'undefined') { // Localstorage
    localStorage.setItem('__state', '1');
  }
  else { // Cookies
    document.cookie = "__state=1";
  }
}

function getCookie(cookie) {
  var ret = false;
  var cookies = document.cookie;
  var pattern = cookie +'=(.*?);';
  var regex = new RegExp(pattern);
  var val = cookies.match(regex);
console.log(val);  
  if (val) ret = val[1];
  
    return ret;
}
</script>

Open in new window

Updated sample here
0
 

Author Comment

by:seeraig
ID: 41771481
Thank Julian. I'll try and test this out later today and let you know if I can get it working.
0
 

Author Comment

by:seeraig
ID: 41774148
Hi Julian,

This seems like I got this working, need to test a little more. What's the best way to delete the cookie, like after checkout?
0
 
LVL 55

Expert Comment

by:Julian Hansen
ID: 41774342
Just set the cookie to a blank value with an expiry date in the past (-1, 0, 1970-01-01 etc)

You can read more on these links

https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie#notes
http://www.w3schools.com/js/js_cookies.asp

I would recommend reading both of those pages through to get a complete understanding of how cookies work.
0

Featured Post

Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
Use these top 10 tips to master the art of email signature design. Create an email signature design that will easily wow recipients, promote your brand and highlight your professionalism.
In this tutorial viewers will learn how to style elements, such a divs, with a "drop shadow" effect using the CSS box-shadow property Start with a normal styled element, such as a div.: In the element's style, type the box shadow property: "box-shad…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question