I want to add a class to the selected ‘li’ and at the same time, remove the class:selected from previous selected li element.
I have worked on it hours and still haven’t got any luck. I also checked others questions, but their solutions don’t work for me.
Help please….
<ul id='mainView' class='menu' style='float: left; clear: both;'>
<a href="/Link1"><li>Patient</li></a>
<a href="/Link2"><li>Recommendations</li></a>
</ul>
<script type="text/javascript">
$(document).ready(function () {
$('.menu ul a').on('click', function (event) {
$('.menu ul a.selected').className = '';
alert($(this).attr('id'));
$(this).attr('class') = 'selected';
});
});
// $('.menu li').on('click', function () {
// $('.menu li.selected').className = '';
// this.className = 'selected';
// });
</script>
Update:
I did put a inside li, but if I click on the li not the a inside of the li, the webpage does not redirect. That’s the reason why I do it in a reversed way.
Update 2
The reason why the selected li does not get the “selected” class is because the whole webpage is redirected to a new page which has the same navigation bar.
So now the question is how to highlight the selected li(it was selected on the previous page) on the new webpage.
Inside an
ULeverybody (even a browser) is expecting to see aLIso your HTML:
And your jQ:
Building web pages you should know how to treat
LIelements. Simple, like dummy containers with minimal styling.That means that you rather add a
display:block…float:leftand other cool stuff to the<A>elements, than setting apaddingthere you go with your full-sized-clickableAelements.Additionally (if you don’t have time to play with CSS) to make a
LIfully clickable use:After the OP late edit – and to answer the question
After the pages refreshes to get which one is the active one use: