Maintain jquery javascript tab when refreshing the page

Asked

Viewed 675 times

2

Good morning, I have the following doubt, I have a system of tabs in javascript but whenever I select a tab and update the page it automatically goes back to the first one which is bad because I intend to put buttons that act with get, How can I keep it in the same tab if I update or get it from the same page? follows code.

<script type="text/javascript">
$(document).ready(function(){
  $("#content div:nth-child(1)").show();
  $(".abas li:first div").addClass("selected");       
  $(".aba").click(function(){
      $(".aba").removeClass("selected");
      $(this).addClass("selected");
      var indice = $(this).parent().index();
      indice++;
      $("#content div").hide();
      $("#content div:nth-child("+indice+")").show();
   });

 $(".aba").hover(
      function(){$(this).addClass("ativa")},
      function(){$(this).removeClass("ativa")}
  );              
});

<div class="TabControl">
    <div id="header">
        <ul class="abas">
            <li>
                <div class="aba">
                    <span>Estatisticas</span>
                </div>
            </li>
            <li>
                <div class="aba">
                    <span>Slides</span>
                </div>
            </li>
            <li>
                <div class="aba">
                    <span>Produtos</span>
                </div>
            </li>
            <li>
                <div class="aba">
                    <span>Serviços</span>
                </div>
            </li>
            <li>
                <div class="aba">
                    <span>Usuarios</span>
                </div>
            </li>
            <li style="float:right;"><div class="aba"><span>Alterar Senha</span></div></li>
        </ul>
    </div>
    <div id="exit">
        <ul>

            <li class="exit"><a href="logoff.php">Sair</a></li>
            <li><input type="text" value="Master" disabled="disabled"></li>
        </ul>
    </div>
    <div id="content">
        <div class="conteudo">
            Conteúdo da aba 1
        </div>
        <div class="conteudo">
            Conteúdo da aba 2
        </div>
        <div class="conteudo">
            <?php include("produtos.php"); ?>
        </div>
        <div class="conteudo">
            Conteúdo da aba 4
        </div>
        <div class="conteudo">
            Conteúdo da aba 5
        </div>
        <div class="conteudo">
            Conteúdo da aba 6
        </div>
    </div>
</div>

2 answers

2


Save the index to which the tab corresponds in localStorage.

<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css'>
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/jquery-ui-bootstrap/0.5pre/assets/css/bootstrap.min.css'>

<style
>body {
  padding: 15px;
}
</style>
<div class="TabControl">
    <div id="header">
        <ul class="nav nav-tabs" id="myTab">
            <li class="active"><a href="#Estatisticas" data-toggle="tab">Estatisticas</a></li>
            <li><a href="#Slides" data-toggle="tab">Slides</a></li>
            <li><a href="#Produtos" data-toggle="tab">Produtos</a></li>
            <li><a href="#Serviços" data-toggle="tab">Serviços</a></li>
            <li><a href="#Usuarios" data-toggle="tab">Usuarios</a></li>
            <li style="float:right;"><div class="aba"><span>Alterar Senha</span></div></li>
        </ul>
    </div>
</div>

 <div id="content">
    <div class="tab-content">
        <div class="tab-pane active" id="Estatisticas">Conteúdo da aba 1</div>
        <div class="tab-pane" id="Slides">Conteúdo da aba 2</div>
        <div class="tab-pane" id="Produtos">Conteúdo da aba 3</div>
        <div class="tab-pane" id="Serviços">Conteúdo da aba 4</div>
        <div class="tab-pane" id="Usuarios">Conteúdo da aba 5</div>
    </div>
</div>


<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js'></script>
<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>

<script>

$('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
   localStorage.setItem('activeTab', $(e.target).attr('href'));
});
// Aqui salva o índice ao qual corresponde a aba. Você pode vê-lo na ferramenta de desenvolvimento do Chrome.

//Obtém os dados da localStorage
var activeTab = localStorage.getItem('activeTab');

// No console, ele mostrará a aba onde você fez o último clique e o 
// salve em "activeTab". Deixo o console para você ver. E quando você der refresh
// no navegador, o último em que você clicou estará ativo.

console.log(activeTab);

if (activeTab) {
   $('a[href="' + activeTab + '"]').tab('show');
}

</script>

localStorage - allows us to store data simply and without expiration, that is, they remain there until we erase by code or by the browser itself.

sessionStorage- its operation is identical to the localStorage, with the difference that the data only last during the session, they will only be deleted when the user closes the browser.

  • worked perfectly thank you

0

I would advise using one local Storage browser, can be done in JS with

var abaAtual = 1;
// Salvar a aba atual quando trocar
localStorage.setItem('abaAtual ', abaAtual);

// Buscar se tem uma aba atual selecionada
var abaAtual = localStorage.getItem('abaAtual');
console.log('Aba Atual: ', abaAtual);

The local Storage is basically a way to save a key-value pair in browser storage

  • Where exactly I can fit this into my code, I’m almost completely layered in javascript :(

  • In your job $(".aba").click(function(){ ... }); that you use to display the clicked tab, you save which one you clicked with localStorage.setItem('abaAtual ', indice) (Indice is your variable that identifies which tab is clicked right? )... and the load of the page you have $(".abas li:first div").addClass("selected"); to leave the first tab as the first one displayed right? Here you use get var abaAtual = localStorage.getItem('abaAtual'); and if it has a value you know which tab to select, and has null you use the same code as before to display the first

  • did not work :( , I believe I did wrong, I did so $(". abas li:first div"). addClass("Selected"); var abakAtual = localStorage.getItem('abaAtual'); $(". tab"). click(Function(){ $(". tab"). removeClass("Selected"); $(this). addClass("Selected"); var Indice = $(this). Parent(). index(); Indice++; ; });

  • When changing tab you are saving the value of the clicked tab’s Dice, if soon after var abaAtual = localStorage.getItem('abaAtual'); you give a alert(abaAtual);you will see that he must give an alert with the correct value saved... But you take the value of Storage, saved in var abaAtual and does nothing with that value, you need to come up with a logic for that value to do something, currently you just read and do nothing, just continue with $(".abas li:first div").addClass("selected"); then always the selected will be the first

  • 1

    And when commenting code use it surrounded by ` to make it easier to read

  • thanks for that last tip, I’m new and I was really wondering how you do it

  • Managed to solve? Don’t forget to mark the answer as correct if it is the case, so you help other people who will have the same doubt in the future

  • I got with the solution of the above friend thanks a lot for the help.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.