How to add <li> class to active and leave it after hover using jQuery ? - GeeksforGeeks

15 Oct, 2020
Bootstrap 4 is an open-source CSS framework used for frontend development of web applications. Bootstrap along with HTML and Javascript enrich the user interface for better user experience. jQuery is a Javascript framework that is used to execute Javascript functions. jQuery has similar functionalities like javascript but the only difference is jQuery includes fewer lines of code. Using jQuery and CSS we can write a code that demonstrates the addition of active class when the cursor hovers over the list item and subsequent removal of active class as the cursor is moved out.
First Approach: In the first approach, we use the hover() method of jQuery. The hover() method triggers or registers both the mouseenter and mouseleave events. The hover() method takes two functions as a parameter. The first parameter is the infunction that must be triggered when the mouse enters the selected item and the second parameter is the outfunction that must be executed when the mouse leaves the selected item. The first parameter is required whereas the second parameter is optional. In this example, we specify the infunction only. If only one function is specified, it runs for both the mouseenter and mouseleave events. Also, the toggleClass() method toggles the active class i.e. adds the active class if it is not present in the <li> item else removes the active class.Syntax:hover(infunction, outfunction)Example:<!DOCTYPE html><html>    <head>        <!-- CSS only -->        <link rel="stylesheet"              href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"               integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z"               crossorigin="anonymous" />        <!-- JS, Popper.js, jquery -->        <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"                 integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"                 crossorigin="anonymous">      </script>        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"                 integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"                 crossorigin="anonymous"></script>        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"                 integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"                 crossorigin="anonymous"></script>          <!--CSS stylesheet-->        <style type="text/css">            .active,            li:hover {                color: red;            }        </style>    </head>    <body>        <ul>            <!--list items without the                 active class initially-->            <li class="li">Item 1</li>            <li class="li">Item 2</li>            <li class="li">Item 3</li>        </ul>          <!-- javascript function to add the active             class to list when hovered over -->        <script type="text/javascript">            $(".li").hover(function () {                //toggleClass() switches the active class                $(this).toggleClass("active");            });        </script>    </body></html>OutputExplanation: The output is checked in the console in the web browser. As the cursor hovers over the list item, we see the active class added to the list item in the console. As the cursor hovers out the active class is removed from the recently hovered item and added to the next item.
Syntax:
hover(infunction, outfunction)
Example:
<!DOCTYPE html><html>    <head>        <!-- CSS only -->        <link rel="stylesheet"              href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"               integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z"               crossorigin="anonymous" />        <!-- JS, Popper.js, jquery -->        <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"                 integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"                 crossorigin="anonymous">      </script>        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"                 integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"                 crossorigin="anonymous"></script>        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"                 integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"                 crossorigin="anonymous"></script>          <!--CSS stylesheet-->        <style type="text/css">            .active,            li:hover {                color: red;            }        </style>    </head>    <body>        <ul>            <!--list items without the                 active class initially-->            <li class="li">Item 1</li>            <li class="li">Item 2</li>            <li class="li">Item 3</li>        </ul>          <!-- javascript function to add the active             class to list when hovered over -->        <script type="text/javascript">            $(".li").hover(function () {                //toggleClass() switches the active class                $(this).toggleClass("active");            });        </script>    </body></html>
Output
Explanation: The output is checked in the console in the web browser. As the cursor hovers over the list item, we see the active class added to the list item in the console. As the cursor hovers out the active class is removed from the recently hovered item and added to the next item.
Second Approach: In the second approach, we add the outfunction to denote an already list item. Here the active class is added on mouseenter and removed on mouseleave. As the mouseleave event is triggered the visited class is added to the recently visited list item.<!DOCTYPE html><html>    <head>        <!-- CSS only -->        <link rel="stylesheet"              href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"               integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z"               crossorigin="anonymous" />        <!-- JS, Popper.js, jquery -->        <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"                 integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"                 crossorigin="anonymous"></script>        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"                 integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"                 crossorigin="anonymous"></script>        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"                 integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"                crossorigin="anonymous"></script>          <!--CSS stylesheet-->        <style type="text/css">            .active,            li:hover {                color: red;            }              .visited {                color: violet;            }        </style>    </head>    <body>        <ul>            <!--list items without the                active class initially-->            <li class="li">Item 1</li>            <li class="li">Item 2</li>            <li class="li">Item 3</li>        </ul>          <!-- javascript function to add the active              class to list when hovered over -->        <script type="text/javascript">            $(".li").hover(                function () {                    //toggleClass() switches the active class                    $(this).toggleClass("active");                },                function () {                    $(this).addClass("visited");                }            );        </script>    </body></html>OutputExplanation: The output is checked in the console in the web browser. As the cursor hovers over the list item, we see the active class added to the list item 2 in the console. Also the list item 1 was previously visited and hence the visited class is added to it and the color of the item turns violet as per the specifications of the visited class in the CSS stylesheet.
<!DOCTYPE html><html>    <head>        <!-- CSS only -->        <link rel="stylesheet"              href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"               integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z"               crossorigin="anonymous" />        <!-- JS, Popper.js, jquery -->        <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"                 integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"                 crossorigin="anonymous"></script>        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"                 integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"                 crossorigin="anonymous"></script>        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"                 integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"                crossorigin="anonymous"></script>          <!--CSS stylesheet-->        <style type="text/css">            .active,            li:hover {                color: red;            }              .visited {                color: violet;            }        </style>    </head>    <body>        <ul>            <!--list items without the                active class initially-->            <li class="li">Item 1</li>            <li class="li">Item 2</li>            <li class="li">Item 3</li>        </ul>          <!-- javascript function to add the active              class to list when hovered over -->        <script type="text/javascript">            $(".li").hover(                function () {                    //toggleClass() switches the active class                    $(this).toggleClass("active");                },                function () {                    $(this).addClass("visited");                }            );        </script>    </body></html>
Output
Explanation: The output is checked in the console in the web browser. As the cursor hovers over the list item, we see the active class added to the list item 2 in the console. Also the list item 1 was previously visited and hence the visited class is added to it and the color of the item turns violet as per the specifications of the visited class in the CSS stylesheet.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
CSS-Misc
HTML-Misc
jQuery-Misc
Picked
CSS
HTML
JQuery
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction)