zouzou b lebiane
zouzou b lebiane

Reputation: 205

Web development show/hide <div> after refresh

I am working on a website for a restaurant that has a header with the following tabs:

I want to switch between the tabs while staying in the same page, but only changing the contents of it according to the chosen tab.

I managed to do that with jQuery by hiding <div>s and showing the one I want by adding and removing classes. The problem is that whenever I refresh the page it returns to the main home page that are set to show when page is loaded.

So my question is: is there a way to make the webpage refresh with the changed classes made???

Upvotes: 0

Views: 1320

Answers (4)

Makan
Makan

Reputation: 617

One way is to use local storage. Simply whenever one of your header tabs is click save something in your local storage using JavaScript. like this:

    localStorage.setItem('page', 'home');

You can over write this value by calling it again and passing a new value into it.

Set display: none; for all of your divs and show them based on your loacal storage value. On the page load you can get the value and show the div with the same id as the local storage value like so:

    var page = localStorage.getItem("page");
    if(page){
        // change the tab based on page's value
        $('div#' + page).show();
    }else{
        // Go to your default page, assuming its default is home page
        $('div#home').show();
    }

You can always see what is saved in your local storage by using Chrome developer tool > Resources > Local Storage.

Remember that you can only store string values in your local storage. But the way around it is to store JSON.stringify and JSON.parse.

If you wanna know more about browser support or anything else you can always read more about local storage:


References:

Upvotes: 0

Felipe Castro
Felipe Castro

Reputation: 1

are you tested the onload of the tag ?

try to put your class changes on a javascript function and ejecute the function in the body tag with onload.

Like this:

Web Code...

function loadClasses(){ JQuery Changes Here.. }

Upvotes: 0

Hank
Hank

Reputation: 1678

Without involving any work from the backend, you can store that information thru localStorage.

Like so:

localStorage.setItem("currentPage", "HomePage");
localStorage.setItem("favoriteColor", "Red");

On page load, you can do some error handling in case these properties have never been set, like so:

if(!localStorage.getItem("currentPage"))
{
    localStorage.setItem("currentPage", "HomePage");
}

Upvotes: 3

Spechal
Spechal

Reputation: 2716

You need to maintain state between reloads, which is generally accomplished via sessions or cookies.

Your server-side language should have a method for that. Such as sessions for PHP. Or you could use cookies locally.

Upvotes: 1

Related Questions