Why is the first "li" menu item ALWAYS kept even if I click another?
If instead of putting the address where each "li" should go, I simply add an href="#" it works for me but with the address it doesn't work.
Code:
$(document).ready(function() {
$('ul li a').click(function() {
$('li a').removeClass("active");
$(this).addClass("active");
});
});
#menu_horizontal li {
list-style: none;
display: inline;
margin-left: 10px;
}
#menu_horizontal li a {
padding: 3px 1em;
border: 1px solid #778;
border-bottom: none;
background: #DDE;
text-decoration: none;
}
#menu_horizontal li a:link {
color: #448;
}
#menu_horizontal li a:hover {
color: white;
background: red;
border-color: #227;
}
#menu_horizontal .active {
background: red;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="menu_horizontal">
<li class="nueva" id="nueva"><a class="active" href="menu_cliente.php?nueva=1">NUEVA OPINIÓN</a></li>
<li class="ver" id="ver"><a href="menu_cliente.php?ver=1">VER OPINIONES</a></li>
<li class="eliminar" id="eliminar"><a href="menu_cliente.php?eliminar=1">ELIMINAR OPINIÓN</a></li>
<li class="datos_cliente" id="datos_cliente"><a href="menu_cliente.php?datos_cliente=1">DATOS PERSONALES</a></li>
</ul>
With CSS it wouldn't be dynamic, because you would have to add a class for each link you have. So jquery simplifies things, every time you click on a link the active class is added to that link, and at the same time it is removed from the link that was active.
I hope to be helpful.
Something could be done just with CSS using the selector
:target
. With:target
will select the element with theid
specified in the URI fragment identifier (the part after the#
).So by changing the link from
menu_cliente.php?nueva=1
tomenu_cliente.php?nueva=1#nueva
, when you click on "new opinion" and reload the page, as the#
with theid
menu option has been added, that option will be activated:As a recommendation: instead of reloading the menu_client.php page every time a menu is clicked, what you could do is make AJAX calls when
#
the page changes.This would give a better user experience because the whole page would not be reloaded, the common part would remain constant and only one main container would change, which would also make your website faster.
You can see an example of that in this other question .