Reputation: 2140
I got a menu on my Mastepage, as below:
<div class="navtop">
<ul class="nav">
<li class=""><a href="Default.aspx">Home</a></li>
<li class=""><a href="Test.aspx">Link</a></li>
<li class=""><a href="Hello.aspx">Link</a></li>
<li class=""><a href="World.aspx">Link</a></li>
</ul>
</div>
To set the class of the <li></li>
to active I am using this Javascript code:
<script>
$("li").click(function () {
alert("this is the message");
if ($("li").hasClass('active')) {
$("li").removeClass('active');
}
$(this).addClass('active');
});
</script>
This should work, because I saw this somewhere and they say it should work. But it doesn't work for me, my menu stays with an empty class="" and the alert-message from the javascript (to test it) doesn't work either.
Can someone help me? What am I doing wrong?
Upvotes: 0
Views: 665
Reputation: 2876
Your code will never work in a simple ASPX page. Once you click on the text you are clicking the anchor and this navegates to another page loading the new page.
Javascript executes in client side but when yo click on the link you are performing a server navigation to other page loading anoder html page that invokes again the $(document).onReady(...) in the new page.
Also if you put the "event.preventDefault();" ad click the selection code works onClick but the navigatión action is not launched and your menu never navigates to the other page.
Yo need to make the selected state in ASPX using marker to detect the current child page used or passing changing a variable in javascript that to load the correct item as active.
I recommend to you if you are using ASPX to use at least the ASPX Menu component with a siteMap this makes to you ASPX code better to maintain.
Build a Menu from the web.sitemap file in ASP.NET
Upvotes: 0
Reputation: 148120
Check you havve added jQuery successfully and bind the event in document.ready event. you code seems to work. You also missed the closing quotes here class="navtop
Adding jQuery
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
Putting code in document.ready
$(document).ready(function(){
$("li").click(function (event) {
event.preventDefault();
if ($("li").hasClass('active')) {
$("li").removeClass('active');
}
$(this).addClass('active');
});
});
Upvotes: 1