2
I would like to leave a selected item when I am in some selected menu. For example, if I am on the link '/about'. The menu item called 'about' should change color, for example. You could do this?
2
I would like to leave a selected item when I am in some selected menu. For example, if I am on the link '/about'. The menu item called 'about' should change color, for example. You could do this?
2
Just add a CSS class and apply it when you click on the element or read the url to know 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 joined a field "data-field". So you can save, in the element, which name to react to. I also gave them a class menu
to facilitate the jQuery selector that will search for these menu elements.
In CSS I created a class called selected
with a specific colour.
In jQuery I will first read the URL. I left a redundancy for the url case that ends with /
. But otherwise, as you showed in your example in a url like www.dominio.com/sobre
he’s gonna get the sobre
.
Then I compare all the menu elements to see what you have data-url="sobre"
and this one will get the new class. The others will remove the class if they have it from before (unlikely if you change page).
Note: I must say, this is a lot cleaner when done on the server side. In this case just add the right class to the element corresponding to the page that will open. But I assume that is not possible.
Thank you very much for your excellent reply, my friend. I only have one more question. I have this html http://jsfiddle.net/felipestoker/Vm7bG/ o data-url
where would I use it, in case? no topoMenuLista
?
@Felipestoker can also put the Javascript of the page. I assume you want to open the respective drop-down as well.
Browser other questions tagged jquery css
You are not signed in. Login or sign up in order to post.
Yes. Dynamically add the class based on
window.location
– Beterraba
You can accomplish this according to the
window.location
and thewindow.location.href
If you don’t succeed like this let me know that when I put something for you.– Ronny Amarante