Hello fellas, in today's post I want to show you guys a cool jQuery trick I learned recently.
When you are creating interactive web pages it is very likely you will need to have a navigation bar that has buttons or links which direct users to other webpages. In some scenarios, you need to display a couple of options for the user to choose from and an easy to use choice for this would be using a bit of jQuery to show a dropdown menu with links on hover.
For this you will need to have jQuery installed at the base of your project and linked to your HTML file as so;
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
Ok so let's hop right into adding the flesh of the project. First, let us create a wrapper that will hold all of our content. Then create a button or just a link that will drop down our options.
<button value="Hover on me!" id="hover">Hover On Me!
The next step is to add the list of options you want to be displayed on hover. In this case, we will create links to other pages.
<li><a href="#">HTML Page</a></li>
<li><a href="#">CSS Page</li></a>
Now we have our HTML all set up. The next step is to set the display of the dropdown options to 'none'. This is because we only want this list of options to appear when we hover over the button and disappear when the mouse moves away.
In your CSS file;
In your JS file add these five lines of code;
What we are simply telling jQuery here is:
- Check if the document is done loading using .ready()
- 'Listen' to the element with the class "button" and check if the user hovers on it using .hover()
- If the user hovers on the element, slide down the dropdown menu using slideToggle()
Note: "slideToggle()" toggles between "slideDown()" and "slideUp()" depending on the element method which in this case is "hover()", hence the dropdown menu will slide down when the user hovers above the button and slide up when the user moves away from the button.
Happy coding and feel free to leave comments down below
Top comments (1)
Huge problem when mouse is hovered on sub-menu - it dissapears...