Div class is active after page refresh


#1

My homepage content is into

      <div class="active">
         Homepage content
       </div>

Class active is removed after some link (link1...link5) is clicked with jquery script

  $(document).ready(function(){
   $("#link-link1 , #link-link2 , #link-link3 , #link-link4 , #link-link5").click(function(){
   $(".active").css("display","none");
})})

It work but when i refresh page, it show my link content and homepage content (class active is visible). You can try it here (and see full code) . Probably i must use cache but i do not have idea how to realize it.


#2

Hi,

Welcome to the forums smile

I've not fully understood what you are trying to do, but if you want to preserve state between page refreshes, you'll need to use some kind of client-side storage.
Local storage, for example.


#3

Check this page : http://skusobnastranka1.php5.sk/ . Click on some link (link1-link5) and refresh your browser. It show homepage content and content of current link. But i need show only content of current link. After refresh it miss my jquery function

$(document).ready(function(){ 
   $("#link-link1 , #link-link2 , #link-link3 , #link-link4 , #link-link5").click(function(){
   $(".active").css("display","none"); 
})})

#4

Ok, I understand now.

As you are hiding and showing your content using JavaScript depending on what your user clicks on, you will need to store a reference to the most recently clicked tab (defaulting to home) and then fetch that reference on page load and display the correct content accordingly.

I would use local storage to do that. This is the basic syntax:

// store
localStorage.setItem("hello", "Hello World!");

// retrieve
console.log(localStorage.getItem("hello"));
     
// delete
localStorage.removeItem("hello");

If this all seems like gobbledygook to you, let me know and I'll make you a demo later on (I'm off out now).


#5

Thanks for reply, yes if you have time for it you can make a demo. I am new to javascript and i cant resolve this problem.


#6

Sure, here's a demo

And here's the code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <base href="http://skusobnastranka1.php5.sk/" />
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 
    <title>Hide / show content with JS</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
      html, body { height:1100px; }
      body { width: 100%; }
      .main {
        height: 1000px;
        width: 900px;
        margin-top: 0px;
        margin-right: auto;
        margin-left: auto;
        border-top-left-radius: 42px;
        border-top-right-radius: 42px;
        -moz-box-shadow: 15px 15px 15px #CCC;
        -webkit-box-shadow: 7px 7px 7px #CCC;
        box-shadow: 20px 20px 20px #000;
        background-color: #DFDEDE;
      }

      .menu {
        height: 60px;
        width: 900px;
        margin-top: 63px;
        margin-right: auto;
        margin-left: auto;
        background-image: url(menu8.jpg);
      }

      .content {
        left:0px;
        top: 93px;
        position:relative;
        padding-bottom: 30px;
      }

      .hcontent {
        margin-top:230px;
        font-size: 25px;
        color:black;  
      }

      #navigation a{
        color: #fff;
        padding-right:25px;
        font-size: 19px;
        position:relative;
        top:15px;
        left:180px;     
      }

      #navigation a:hover { color: #000; }

      ul {
        width: 500px;
        display: table;
        table-layout: fixed;
      }

      ul li { display: table-cell; }

      .panel{
        min-width: 65%;
        overflow-y: hidden;
        overflow-x: hidden;
        display: none;
      }
    </style>
  </head>
  <body>  

  <div class="main">
    <div class="content">
      <div class="menu">      
        <ul id="navigation">
          <li><a data-tab="#home" href="#">Home</a></li>
          <li><a data-tab="#link1" href="#">link1</a></li>
          <li><a data-tab="#link2" href="#">link2</a></li>
          <li><a data-tab="#link3" href="#">link3</a></li>
          <li><a data-tab="#link4" href="#">link4</a></li>
          <li><a data-tab="#link5" href="#">link5</a></li>
        </ul>
      </div>
    </div>

    <div id="home" class="panel">
      <div class="hcontent">
        Homepage content 
      </div>
    </div>

    <div id="link1" class="panel">
      <div class="hcontent">
        Link 1 Content
      </div>
    </div>

    <div id="link2" class="panel">
      <div class="hcontent">
        Link 2 Content
      </div>
    </div>

    <div id="link3" class="panel">
      <div class="hcontent">
        Link 3 Content
      </div>
    </div>

    <div id="link4" class="panel">
      <div class="hcontent">
        Link 4 Content
      </div>
    </div>

    <div id="link5" class="panel">
      <div class="hcontent">
        Link 1 Content
      </div>
    </div>
  </div>   

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>      
  <script>
    $("#navigation a").on("click", function(e){
      e.preventDefault();
      var currTab = $(this).data("tab");
      localStorage.setItem("currentTab", currTab);
      $(".panel").hide();
      $(currTab).fadeIn();
    });

    var lastSelectedTab = localStorage.getItem("currentTab");
    if (!lastSelectedTab) {
      lastSelectedTab = "#home";
    }
    $(lastSelectedTab).fadeIn();
  </script>       
  </body>
</html>

Any questions, just let me know.


How to add class in the active link to highlight the data-tab?
#7

Thanks so much for your help. I have last question .Can i use it for save background image? In my real site ( no this example) i change background with jquery script. When i click on some link (link1 ... link5) it change body background. Jquery:

$("#link-home").click( function(){ $
    ("body").removeClass("bg2 bg3").addClass("bg1");
    });

    $("#link-link1").click( function(){ $
    ("body").removeClass("bg1 bg3 ").addClass("bg2");
    });

    $("#link-link2").click( function(){ $
    ("body").removeClass("bg1 bg2 ").addClass("bg3");
    });

But when i refresh page it change background to default body background. I tried this script but it is not working for me.

$(window).ready(function() {
    var switchBackground = function(bg) {
        var savedBackgorund = window.localStorage.activeBackground;
        var bg = typeof bg !== 'undefined' ? bg :
            (savedBackground ? savedBackground : 'bg1');
        $('body').removeClass('bg1 bg2 bg3').addClass(bg);
        window.localStorage.activeBackground = bg;
    }

    switchBackground();

    $("#link-home").click( function() {
        switchBackground("bg1");
    });

    $("#link-link1").click( function() {
        switchBackground("bg2");
    });

    $("#link-link2").click( function() {
        switchBackground("bg3");
    });
});

#8

Sure, I updated my demo.

Here's the new code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- http://www.sitepoint.com/forums/showthread.php?1203821-div-class-is-active-after-page-refresh -->
    <base href="http://skusobnastranka1.php5.sk/" />
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 
    <title>Hide / show content with JS</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
      html, body { height:1100px; }
      body { width: 100%; }
      .main {
        height: 1000px;
        width: 900px;
        margin-top: 0px;
        margin-right: auto;
        margin-left: auto;
        border-top-left-radius: 42px;
        border-top-right-radius: 42px;
        -moz-box-shadow: 15px 15px 15px #CCC;
        -webkit-box-shadow: 7px 7px 7px #CCC;
        box-shadow: 20px 20px 20px #000;
        background-color: #DFDEDE;
      }

      .menu {
        height: 60px;
        width: 900px;
        margin-top: 63px;
        margin-right: auto;
        margin-left: auto;
        background-image: url(menu8.jpg);
      }

      .content {
        left:0px;
        top: 93px;
        position:relative;
        padding-bottom: 30px;
      }

      .hcontent {
        margin-top:230px;
        font-size: 25px;
        color:black;  
      }

      #navigation a{
        color: #fff;
        padding-right:25px;
        font-size: 19px;
        position:relative;
        top:15px;
        left:180px;     
      }

      #navigation a:hover { color: #000; }

      ul {
        width: 500px;
        display: table;
        table-layout: fixed;
      }

      ul li { display: table-cell; }

      .panel{
        min-width: 65%;
        overflow-y: hidden;
        overflow-x: hidden;
        display: none;
      }

      .bg-home{
        background-image: url(http://2.bp.blogspot.com/-SnAt-pfJbpI/Tp3-Da8vT_I/AAAAAAAAAEc/5iflZyp3Zb0/s1600/trashcat.jpg);
      }
      .bg-link1{
        background-image: url(http://www.lolcats.com/images/u/12/43/lolcatsdotcomlikemyself.jpg);
      }
      .bg-link2{
        background-image: url(http://images2.fanpop.com/images/photos/2900000/LOL-CATS-lol-cats-2985219-772-726.jpg);
      }
      .bg-link3{
        background-image: url(https://i.chzbgr.com/maxW500/6073452544/h4B353A81/);
      }
      .bg-link4{
        background-image: url(http://momvsmarathon.sanitydepartment.com/wp-content/uploads/2012/01/lol-cats_gheck-out-my-guns2.jpg);
      }
      .bg-link5{
        background-image: url(http://www.lol-cat.org/wp-content/uploads/2013/03/3-best-lolcats-funny-images-of-cats.jpg);
      }
   </style>
  </head>
  <body>  

  <div class="main">
    <div class="content">
      <div class="menu">      
        <ul id="navigation">
          <li><a data-tab="#home" href="#">Home</a></li>
          <li><a data-tab="#link1" href="#">link1</a></li>
          <li><a data-tab="#link2" href="#">link2</a></li>
          <li><a data-tab="#link3" href="#">link3</a></li>
          <li><a data-tab="#link4" href="#">link4</a></li>
          <li><a data-tab="#link5" href="#">link5</a></li>
        </ul>
      </div>
    </div>

    <div id="home" class="panel">
      <div class="hcontent">
        Homepage content 
      </div>
    </div>

    <div id="link1" class="panel">
      <div class="hcontent">
        Link 1 Content
      </div>
    </div>

    <div id="link2" class="panel">
      <div class="hcontent">
        Link 2 Content
      </div>
    </div>

    <div id="link3" class="panel">
      <div class="hcontent">
        Link 3 Content
      </div>
    </div>

    <div id="link4" class="panel">
      <div class="hcontent">
        Link 4 Content
      </div>
    </div>

    <div id="link5" class="panel">
      <div class="hcontent">
        Link 5 Content
      </div>
    </div>
  </div>   

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>      
  <script>
    $("#navigation a").on("click", function(e){
      e.preventDefault();
      var currTab = $(this).data("tab"),
          bodyClassName = "bg-" + currTab.replace(/#/, "");
      localStorage.setItem("currentTab", currTab);
      localStorage.setItem("bodyClassName", bodyClassName);
      $(".panel").hide();
      $(currTab).fadeIn();

      document.body.className = bodyClassName;
    });

    var lastSelectedTab = localStorage.getItem("currentTab"),
        lastBodyClassName = localStorage.getItem("bodyClassName");

    if (!lastSelectedTab) {
      lastSelectedTab = "#home";
      lastBodyClassName = "bg-home"
    }
    $(lastSelectedTab).fadeIn();
    document.body.className = lastBodyClassName;
  </script>       
  </body>
</html>

#9

Pullo thanks a lot. Your method work great. Only one thing is negative that now it doesnt show link category in browser www.webpage.com#home || www.webpage.com#link1 ... But i am trying resolve it.


#10

To do that, just remove this: e.preventDefault();
This prevents the browser from executing the element's default action (in this case, following the link).

This might not be a good idea, however, as this will cause the page to jump to that location.
Why do you need urls in this form?


#11

I need urls in this form because its better for orientation on a webpage. I am working on a sport stream webpage. It is needed to use urls form #specific-location because i want to use more channels . Example: Main category: football subcategories: Channel1 Channel2 ... . If i click on link Channel1 it change only main div content . Somethink like this

<!DOCTYPE HTML>
<html>
<head>
<title> Untitled </title>
<script type="text/javascript">
// From: http://www.webdeveloper.com/forum/showthread.php?266743-Switch-Div-Content-Using-Javascript&p=1229155#post1229155

function showDiv(idInfo) {
  var sel = document.getElementById('divLinks').getElementsByTagName('div');
  for (var i=0; i<sel.length; i++) {
    sel[i].style.display = 'none';
  }
  document.getElementById('container'+idInfo).style.display = 'block';
}
</script>
<style type="text/css">
#container1, #container2, #container3, #container4 {
  display:none;
  border:3px solid blue;
  height:200px;
  overflow:hidden;
}
</style>

</head>
<body>
<div id="linkDiv">
 <a href="#as" onclick="showDiv('');return false">Home</a>
 <a href="#sasa" onclick="showDiv('1');return false">link 1</a>
 <a href="#" onclick="showDiv('2');return false">link 2</a>
 <a href="#" onclick="showDiv('3');return false">link 3</a>
 <a href="#" onclick="showDiv('4');return false">link 4</a>
</div>
<p>

<div id="container">
 The container I want all content divs to load into... and by default, to show the first container content
</div>

<!-- The 4 container content divs. -->
<div id="divLinks">
 <div id="container1">Container #1<p>Whole bunch of text 1</div>
 <div id="container2">Container #2<p>Whole bunch of text 2</div>
 <div id="container3">Container #3<p>Whole bunch of text 3</div>
 <div id="container4">Container #4<p>Whole bunch of text 4</div>
</div>

</body>
</html>

<snip/>


#12

Why do you need urls in this form?

It might also help users send links to an exact part of the page to a friend... the friend can
- see the name of the part (channel)
- jump right to it on page load

I was making one of those stupid one-big-page-as-website things and using a Javascript scrollTo thing which, with preventDefault() removed the destination... and during this I realised I did want the hashes in the URLs. Just didn't want the history (back button should take the user off the page and to wherever they were before they landed here), historyAPI can fix that.

Loved the localstorage example, I've actually never used it and was thinking of it recently, and now just happen to run across your post! smile


#13

I did not realize this. Back button doesn't work so i try historiAPI. And other think. If web browser is re-open it start on lastSelectedTab. So i tried fix it with

window.onbeforeunload = function() {
  localStorage.removeItem("currentTab"); };

it remove localstorage but it remove localstorage with refresh too. And it doesnt delete hash.

window.onbeforeunload = function() {
   lastSelectedTab = "#home";
      lastBodyClassName = "bg-home";
};

it doesnt work and i do not understand why this example doesnt work.


#14

If you only want the tab stored during the time the browser is open, then instead of localstorage (which acts like a cookie, and browsers don't forget cookies when you close them either, unless you set your browser up to do that), you can use

sessionStorage.

It's otherwise very similar, but a "session" is from the time the user opens the browser and the page, until they close the browser. The session ends, the values are dumped.

You also don't want to return: false in your HTML-- if javascript doesn't load, or if the user's browser is old enough to not have local/session storage, then you at least still want the links to do something, right? Just won't be pretty, (all options would show and user would jump down to an id on the page matching the hash in the link's URL), but will work.


#15

It work thanks man. So i go on History API. Here is WebStorage support : http://caniuse.com/namevalue-storage I like that mobile browsers have good support. Disabled Javascript you can fix with <noscript>Your browser does not support JavaScript!</noscript> .


#16

[ot]

I don't think that fixes anything, and speaking personally, that particular wording annoys lumps out of me. smile My browser supports JavaScript perfectly well; I choose to browse with it disabled.[/ot]


#17

I just teach English. I am from non-English speaking country. ... Internet Explorer and Android do not support historiAPI. Is there an alternative?


#18

Stomme poes was pointing out that you need to ensure the links will work without JavaScript. Simply adding a statement saying "Your browser does not support JavaScript!" doesn't make that happen. Not everyone affected will be able or know how to enable JS, or to upgrade their browser.

My point is that the wording of that message annoys me. I have chosen to disable JavaScript, so to tell my my browser doesn't support it is just wrong. I also object to messages which say "you must enable JavaScript to use this site" or something similar. I prefer something along the lines of "This site works best with JavaScript enabled".

But the site should function without JavaScript, even if it's not very pretty.


#19

It is good idea. But there is other alternative how to do it. With hash. Homepage content is into

<div class="active" id="homepage">
    obsah domovskej stránky
   </div>

And JS to test my hash and remove class active / add class inactive:

<script type="text/javascript">
     $(document).ready(function(){
var hashStr = location.hash.replace("#","");
if (hashStr>"")
  {
    $("#homepage").removeClass('active').addClass('inactive');
  }
  });
      </script>

It work for links content. But how to rebuild for links content+ change images?
Imager are defined in css:

.bg1{
        background-image: url(../Unnamed%20Site%202/ff%20copy7.jpg) no-repeat; background-size: 1700px 1165px;);
      }
      .bg2{
        background-image: url(../Unnamed%20Site%202/ff%20copy7.jpg);
      }
      .bg3{
        background-image: url(hockeyback.jpg);
      }

Is it possible?


#20

Thanks.
I've been using it for a few things lately. As it doesn't get sent to the server with every request, it much more lightweight than cookies.

Admittedly, "Mmmm, localstorage!" doesn't have the same ring smile