Reputation: 153
I need to dynamically assenare the class "active" to manage the styles of some links. I have this code but does not work ..
<script type="text/javascript" language="javascript">
function locationPathname(){
var path = window.location.pathname.split('/');
path = path[path.length-1];
alert(path);
if (path !== undefined) {
$('livello2 a[href="/' + path + '"]').addClass('active');
}
}
</script>
and html:
<div class="livello2">
<div class="live">
<a href="./Live.php"><img src="live_off.png"></a>
</div>
<nav class="menu">
<ul>
<a href="./index.php" ><li>HOME</li></a>
<a href="./Concerti.php"><li>CONCERTI</li></a>
</ul>
</nav>
</div>
css:
.active{background-color:red}
anyone has any suggestions or sees it off?
Upvotes: 0
Views: 113
Reputation: 12569
In your JS you do this:
$('.livello2 a[href="/' + path + '"]')
(assuming you have added that dot in the beginning of the selector) that would be converted (after calculating the path
variable) into something like
$('.livello2 a[href="/Concerti.php"]')
But the actual href attributes in your code start with a .
(dot) like
href="./Concerti.php"
So you need to update the JS snippet above to
$('.livello2 a[href="./' + path + '"]')
Upvotes: 1
Reputation: 12569
In addition to the answer from @Murali Prasanth about adding dot in your JS snippet, I would suggest to make sure your javascript block is put right after the closing </body>
. If it is in the it's not going to work because pages doesn't know about .livello2
yet – it has not been loaded yet. so, either put JS right before closing </body>
or wrap you javascript code like this:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
function locationPathname(){
…
}
});
</script>
Upvotes: 0
Reputation: 3498
replace this one
$('livello2 a[href="/' + path + '"]')
with this one
$('.livello2 a[href="/' + path + '"]')
Upvotes: 0