I have a menu that when I click on something the menu becomes active and is highlighted.
The code works fine, I don't know if it's a problem in the blazor or it's something in my code anyway.
But what's happening is the following, when I open the application and I click once on some of the menus nothing happens, then if I click again the menu starts to work normally with just one click
HTML Code:
<div>
<ul class="nav" onclick="ActiveTest()">
<li>
<a href="#" class="active">
<i class="fas fa-home"></i>
<span class="name">Home</span>
</a>
</li>
<li>
<a href="#">
<i class="fas fa-book-reader"></i>
<span class="name">Reader</span>
</a>
</li>
...
</ul>
</div>
JS:
function ActiveTest() {
$(".nav li a").click(function () {
$(".nav li a").removeClass("active");
$(this).addClass("active");
});
}
Anyone who has had this problem can tell me a way to make this work without this two-click issue when the app is opened
CodePudding user response:
The first click you are calling ActiveTest which then adds the click event to all the <li>
in your code.
You probably want something like this instead.
HTML
<div class="bar">
<ul class="nav">
<li >
<a href="#" onclick="OpenMenu(this)" class="active">
<i class="fas fa-home"></i>
<span class="name">Home</span>
</a>
</li>
<li>
<a href="#" onclick="OpenMenu(this)">
<i class="fas fa-book-reader"></i>
<span class="name">Reader</span>
</a>
</li>
</ul>
</div>
JS
function OpenMenu(el) {
$(".nav li a").removeClass("active");
$(el).addClass("active");
}