change class of the clicked element

3

So guys I have a list:

<ul class="nav nav-tabs" id="myTab">
   <li class="active"><a href="#novas"><span class="badge badge-info"><?php echo $qtd_novas ?></span> Novas Mensagens</a></li>
   <li><a href="#andamento">Em Andamento</a></li>
   <li><a href="#resolvidas">Resolvidas</a></li>
   <li><a href="#canceladas">Canceladas</a></li>
   <li><a href="#pendentes">Pendentes</a></li>
</ul>

The first line has a class="active" that arrow the tab that will be shown first, well my question is as follows, how do I create a function in javascript to always save the last tab clicked, since I want it when the user quits of the page and then return to it the last tab that he clicked is shown first

    
asked by anonymous 10.04.2015 / 21:43

4 answers

2

I believe this sample code snippet will meet your need. Mainly because this code considers the case where the user comes from any link that points to the desired "tab".

I have chosen to write native JS code, but you can also simplify it with jQuery.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Exemplo</title>
	<style type="text/css">
		#myTab > li.active {
			background: #808080; /* Exemplo */
		}
	</style>

	<script>
		var hashchange_handler = function () {
			var hash = window.location.hash;

			/* É interessante que neste ponto sejam filtrados os valores válidos */

			var myTabs = document.getElementById('myTab');

			var active;
			while(active = myTab.querySelector('#myTab > li.active'))
				active.classList.remove("active");
			
			active = myTab.querySelector('#myTab > li > a[href="' + hash + '"]')
			active.parentNode.classList.add("active");
		}

		if(window.location.hash)
			window.addEventListener("load", hashchange_handler)
		window.addEventListener("hashchange", hashchange_handler);
	</script>
</head>
<body>
	<ul class="nav nav-tabs" id="myTab">
		<li class="active"><a href="#novas"><span class="badge badge-info"><?php echo $qtd_novas ?></span> Novas Mensagens</a></li>
		<li><a href="#andamento">Em Andamento</a></li>
		<li><a href="#resolvidas">Resolvidas</a></li>
		<li><a href="#canceladas">Canceladas</a></li>
		<li><a href="#pendentes">Pendentes</a></li>
	</ul>
</body>
</html>
    
10.04.2015 / 22:25
2

I made an example using localstorage , which is nothing more than a local key / value store that persists beyond the closing of the browser.

The only thing I had to do is to store the ID of the last element clicked, and redo the element using jQuery trigger on the next page load by reading the previously stored ID. But it may be another way without jQuery, the important thing is to smud the click in some way.

Functional example

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.min.js"></script>
    <script type="text/javascript">
        $(function() {
            $("#tabs > li").click(function() {
                $(this).siblings().removeClass("ativo");
                $(this).addClass("ativo");
                localStorage.setItem("ultimo", $(this).attr("id"));
            });

            var ultimo = localStorage.getItem("ultimo");
            if (ultimo)
                $("#" + ultimo).click();
        });
    </script>
    <style>
        li {
            background-color: #FFF;
            cursor: pointer;
            border: 1px solid black;
            padding: 10px;
            display: inline-block;
        }
        li.ativo {
            background-color: #DDF;
        }
        ul {
            list-style-type: none;
        }
    </style>
</head>
<body>
    <ul id="tabs">
        <li id="tabA">A</li>
        <li id="tabB">B</li>
        <li id="tabC">C</li>
        <li id="tabD">D</li>
    <ul>
</body>
</html>
    
10.04.2015 / 22:03
1

A workaround may involve using the cookie property:

Document.cookie

  

Obtain and set cookies associated with the current document.

Specifications can be read at: DOM Level 2: HTMLDocument. cookie

Compatibility

The solution outlined below only needs basic support (read, write), and in terms of compatibility we can observe that the solution works virtually in any browser:

┌────────────────────────────────────────────────────────────────────────┐
│                           Suporte em Desktop                           │
├────────┬─────────────────┬───────────────────┬───────┬─────────────────┤
│ Chrome │ Firefox (Gecko) │ Internet Explorer │ Opera │ Safari (WebKit) │
├────────┼─────────────────┼───────────────────┼───────┼─────────────────┤
│ Sim    │ Sim             │ Sim               │ Sim   │ Sim             │
└────────┴─────────────────┴───────────────────┴───────┴─────────────────┘

┌────────────────────────────────────────────────────────────────────────────┐
│                              Suporte em Mobile                             │
├─────────┬────────────────────────┬──────────┬──────────────┬───────────────┤
│ Android │ Firefox Mobile (Gecko) │ IE Phone │ Opera Mobile │ Safari Mobile │
├─────────┼────────────────────────┼──────────┼──────────────┼───────────────┤
│ Sim     │ Sim                    │ Sim      │ Sim          │ Sim           │
└─────────┴────────────────────────┴──────────┴──────────────┴───────────────┘

Code

The relevant part is in JavaScript, where we will read and write the cookie so that we can load the correct tab when the visitor returns:

/* document.cookie devolve todos os cookies acessíveis pelo presente documento.
 * Tão cedo quanto possível, realizamos uma filtragem para ficar apenas
 * com o valor do cookie que nos interessa.
 */
$(function(){
    var ultimaTab = document.cookie.replace(/(?:(?:^|.*;\s*)tabAtiva\s*\=\s*([^;]*).*$)|^.*$/, "$1");
    $('a[href="'+ultimaTab+'"').trigger("click");
});

/* Twitter Bootstrap tem eventos associados às tabs, pelo que podemos fazer uso
 * dos mesmos para que ao ser apresentada uma nova tab, estejamos também a guardar
 * a sua identificação no nosso cookie.
 */    
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
    var tab = $(this).attr("href");
    document.cookie = "tabAtiva="+tab+"; expires=Fri, 28 Dec 2040 23:59:59 GMT; path=/";
});

Example

This example is also available on JSFiddle where we can access it, change tab, close the browser tab, re-access the JSFiddle and check that the tab open at the time we close the tab is effectively the one that is open when we return to JSFiddle.

$(function(){
    var ultimaTab = document.cookie.replace(/(?:(?:^|.*;\s*)tabAtiva\s*\=\s*([^;]*).*$)|^.*$/, "$1");
    $('a[href="'+ultimaTab+'"').trigger("click");
});

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
    var tab = $(this).attr("href");
    document.cookie = "tabAtiva="+tab+"; expires=Fri, 28 Dec 2040 23:59:59 GMT; path=/";
});
body{
    padding:10px;
    font-size:9px;
}
.tab-content{
    padding-top:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<ul class="nav nav-tabs" role="tablist" id="myTab">
    <li role="presentation" class="active">
        <a href="#novas" aria-controls="novas" role="tab" data-toggle="tab">Novas Mensagens</a>
    </li>
    <li role="presentation">
        <a href="#andamento" aria-controls="andamento" role="tab" data-toggle="tab">Em Andamento</a>
    </li>
    <li role="presentation">
        <a href="#resolvidas" aria-controls="resolvidas" role="tab" data-toggle="tab">Resolvidas</a>
    </li>
    <li role="presentation">
        <a href="#canceladas" aria-controls="canceladas" role="tab" data-toggle="tab">Canceladas</a>
    </li>
    <li role="presentation">
        <a href="#pendentes" aria-controls="pendents" role="tab" data-toggle="tab">Pendentes</a>
    </li>
</ul>
<div class="tab-content">
    <div role="tabpanel" class="tab-pane active" id="novas">
        A minha tab com as novas entradas
    </div>
    <div role="tabpanel" class="tab-pane" id="andamento">
        Assuntos em andamento
    </div>
    <div role="tabpanel" class="tab-pane" id="resolvidas">
        Cenas resolvidas
    </div>
    <div role="tabpanel" class="tab-pane" id="pendentes">
        Cenas pendentes
    </div>
    <div role="tabpanel" class="tab-pane" id="canceladas">
        Cenas canceladas
    </div>
</div>

In the example using the snippet of the SE, the example fails because of the way it is loaded.     

11.04.2015 / 17:06
0

While I was developing my other solution, user Miguel Angelo posted another solution that suits the case. I take this opportunity to post a solution containing both my proposal and his proposal as we have benefits in both cases:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Exemplo</title>
	<style type="text/css">
		#myTab > li.active {
			background: #808080; /* Exemplo */
		}
	</style>

	<script>
		var hashchange_handler = function () {
			
			// Identifica o hash-part do endereço
			var hash = window.location.hash; 

			// Se a hash-part não tiver sido definido no endereço,
			// Exibe o último tab visitado.
			if (!hash && localStorage)
				hash = localStorage.getItem("ultimo"); // Miguel Angelo
			
			// Caso não especificarmos o tab a ser exibido no endereço,
			// e o usuário não tiver um último visitado, elegemos um padrão
			if (!hash)
				hash = '#novas'; // Default

			/* É interessante que neste ponto sejam filtrados os valores válidos */

			var myTabs = document.getElementById('myTab');

			var active;
			while(active = myTab.querySelector('#myTab > li.active'))
				active.classList.remove("active");
			
			active = myTab.querySelector('#myTab > li > a[href="' + hash + '"]')
			active.parentNode.classList.add("active");

			if(localStorage)
				localStorage.setItem("ultimo", hash); // Miguel Angelo
		}

		window.addEventListener("load", hashchange_handler)
		window.addEventListener("hashchange", hashchange_handler);
	</script>
</head>
<body>
	<ul class="nav nav-tabs" id="myTab">
		<li class="active"><a href="#novas"><span class="badge badge-info"><?php echo $qtd_novas ?></span> Novas Mensagens</a></li>
		<li><a href="#andamento">Em Andamento</a></li>
		<li><a href="#resolvidas">Resolvidas</a></li>
		<li><a href="#canceladas">Canceladas</a></li>
		<li><a href="#pendentes">Pendentes</a></li>
	</ul>
</body>
</html>
    
10.04.2015 / 22:52