change class of the clicked element

Asked

Viewed 3,380 times

3

so guys I got 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 doubt is the following, as I create a function in javascript to always save the last tab clicked, because I want when the user leaves the page and then back to the same the last tab that he clicked is shown first

  • If it’s not single page you will need to use some way to store the latter tab clicked on the client. For example, with localStorage or sessionStorage.

  • how so single page? I think I’m misinterpreting your answer kkk

4 answers

2

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

The only thing I had to do is store the ID of the last clicked element, and click the element again using trigger jQuery on the next page load, reading the previously stored ID. But it can be another way without jQuery, the important thing is to smudge the click somehow.

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>
  • in the case of a ul li utilise $("$nome_id ul li").click(function() {}) ?

  • I made a change to show you how it looks with ul and li.

2

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

I chose 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>

1

A solution can go through the use of property cookie:

Document cookie.

Get and set the cookies associated with the current document.

Specifications can be read in: DOM Level 2: Htmldocument.cookie

Compatibility

The solution 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 at Jsfiddle where we can access it, change tab, close the browser tab, go back to Jsfiddle and check that the tab opened at the time we close the tab is effectively the one opened 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>
<script src="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 SE, the example fails due to the way it is loaded.

0

While I was developing my other solution, user Miguel Angelo posted another solution that meets the case. I take the opportunity to post a solution containing both my proposal and his since 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>

  • When I change the li clicked (tested by clicking on the third, Resolvidas) and reload the page, the active back to the first li Novas Mensagens (FF 37).

  • Renan, I believe that the page is not firing the event "load" correctly, which browser you use?

Browser other questions tagged

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