I'd like to leave a selected item when I'm on any selected menu. For example, if I'm on the '/ on' link. The menu item called 'on' should change color, for example. Would you be able to do that?
I'd like to leave a selected item when I'm on any selected menu. For example, if I'm on the '/ on' link. The menu item called 'on' should change color, for example. Would you be able to do that?
Just add a CSS class and apply it when you click on the element or read the url to find out where it is
An example:
HTML
<div class="menu" data-url="sobre">Sobre a empresa</div>
CSS
.selected {
color: #aac;
}
jQuery
var url = document.URL.split('/');
// em vez do document.URL pode usar também window.location.href ou window.location.pathname
url = url[url.length - 1] || url[url.length - 2];
console.log(url); // aqui vai dar-lhe o url em que está
$('.menu').each(function () {
var self = $(this);
if (self.data('url') == url) {
self.addClass('selected');
return;
}
self.removeClass('selected');
});
In HTML I've added a " data-field field." This way you can save the name to which you want to react in the element. I also gave them a menu
class to facilitate the jQuery selector that will look up these menu elements.
In CSS I created a class called selected
with a specific color.
In jQuery I'll first read the URL. I left a redundancy for the url case that ends with /
. But otherwise, as shown in your example in a url like www.dominio.com/sobre
it will catch sobre
.
Then I compare all the elements of the menu to know what has data-url="sobre"
and this will receive the new class. The others remove the class if they have it from before (unlikely if you change pages).
Note: I should say that this is much cleaner when done server side. In this case just add the right class to the element corresponding to the page that will open. But I presume it will not be possible for you.