I am still new on jquery and this is the problem that I am currently facing. What I'm trying to do is to put hover and click event on the menu of a webpage, hover event works perfectly but click event is not working. Where should I fix? also, is it possible to combine the hover and click event to make the code shorter? Thank you in advance for the help.
Here is my code:
$(document).ready(function() {
$(".navi li a:first").addClass("active");
$(".navi li a").hover(function() {
$(this).addClass("active");
}, function() {
$(this).removeClass("active");
});
$(".navi li a").click(function() {
$(".navi li a").removeClass("active");
$(this).addClass("active");
});
}); //end
.navi>li a.active {
color: #0a2a43;
background-color: rgba(255, 255, 255, 0.8);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav>
<ul class="navi">
<li><a href="#" class="active">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Work</a></li>
<li><a href="#">Contact</a></li>
</ul>
<!--navi-->
</nav>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You don't need to handle the "hover" in your jQuery, let the power of CSS do that
I've also improved your jQuery, so you're not getting the collection of elements time and time again... and changed the CSS so it's more obvious when the .active
or :hover
is used.
Additionally, you are effectively setting the .active
on the first element both in the HTML and the jQuery... no need to do both, so for this example I've remove the HTML attribute.
// Simpler "ready" format
$(function() {
// Get all the elements once
var $a = $(".navi li a");
// Set the first one to "active"
$a.first().addClass("active");
// Click event
$a.on("click", function(e) {
// Stop navigation
e.preventDefault();
// Remove from all
$a.removeClass("active");
// Add to clicked
$(this).addClass("active");
});
}); //end
.navi>li a.active,
.navi>li a:hover{
color: red;
background-color: rgba(0, 0, 0, 0.8);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav>
<ul class="navi">
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Work</a></li>
<li><a href="#">Contact</a></li>
</ul>
<!--navi-->
</nav>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>