-1

I have created a navigation bar with a :hover effect and I'd like to know how to make that effect persistent, even after the cursor is removed from the area. The effect is a background color under the given word. For example, when Home is selected I'd like for that effect to stay on the element until another element (for example, Register) is clicked.

.navbar {
    list-style-type: none;
    background-color: black;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin: 0;
    height: 50px;
    padding: 0;
}

.navbar a {
    text-decoration: none;
    color: gray;
    padding: 17px;
    transition: background-color 0.5s linear;
}

.navbar a:hover {
    background-color: green;
    color: honeydew;
}

body {
    margin: 0;
}
<header>
    <nav>
        <ul class='navbar'>
            <li><a href='#home'>Home</a></li>
            <li><a href='#download'>Download</a></li>
            <li><a href='#register'>Register</a></li>
            <li><a href='#contact'>Contact</a></li>
            <li><a href='#FAQ'>FAQ</a></li>
        </ul>
    </nav>
</header>
Mat Sz
  • 2,524
  • 1
  • 10
  • 23

1 Answers1

2

The desired effect can be achieved with just CSS but it's tricky and the only way I know of would cause your links to become non-functional (since it requires replacing your links with <input type="radio">). So overall, I would recommend to use JavaScript for this.

The JavaScript way would be, using jQuery, to add a class when the mouseover event is triggered and to remove it from all other elements on another desired event getting triggered.

Example: (I have replaced the :hover pseudoselector with a .hover class selector and added the jQuery library and required code.)

jQuery is not required to achieve this effect, you can do this just fine with vanilla JavaScript.

$(".navbar a").on("mouseover", function () {
    $(".navbar a").removeClass("hover");
    $(this).addClass("hover");
});
.navbar {
    list-style-type: none;
    background-color: black;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin: 0;
    height: 50px;
    padding: 0;
}

.navbar a {
    text-decoration: none;
    color: gray;
    padding: 17px;
    transition: background-color 0.5s linear;
}

.navbar a.hover {
    background-color: green;
    color: honeydew;
}

body {
    margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
    <nav>
        <ul class='navbar'>
            <li><a href='#home'>Home</a></li>
            <li><a href='#download'>Download</a></li>
            <li><a href='#register'>Register</a></li>
            <li><a href='#contact'>Contact</a></li>
            <li><a href='#FAQ'>FAQ</a></li>
        </ul>
    </nav>
</header>
Mat Sz
  • 2,524
  • 1
  • 10
  • 23