Creating a central navigation menu for a website

Currently, I am working on incorporating a menu in the center of a webpage (please note that this is not a top navigation menu).

Here is the initial setup: https://i.sstatic.net/3arql.png

Users are able to click on various menu items to access different content. https://i.sstatic.net/vGILN.png

I have written code for one menu item which functions correctly... however, I am in search of a more elegant solution that can be applied to all menu items.

<script> 
    $(function() {
      $("#menu3").click(function(){
          $(this).css({
            'text-decoration':'underline',
            'font-family':'Gotham-Medium'
          });
          $("#content1").hide();
          $("#content3").show();          
      });
    }); 
</script>


  <nav class="menu">
    <ul>
      <li><div id="menu1">menu1</div></li>
      <li><div id="menu2">menu2</div></li>
      <li><div id="menu3">menu3</div></li>
      <li><div id="menu4">menu4</div></li>
    </ul>
  </nav>

In addition, I created code for the hover state of a menu item. Strangely, everything works using this code:

<script> 
    $(function() {
      $("#menu3").mouseenter(function(){
          $(this).css({
            'text-decoration':'underline',
            'font-family':'Gotham-Medium'
          }); 
      });
    }); 
</script>

However, once I add the mouseleave code, the functionality ceases (including the hover effect on enter, so nothing happens when hovering over the menu). I'm unsure of what is causing this or how to resolve it. Thank you for your help in advance.

<script> 
    $(function() {
      $("#menu3").mouseenter(function(){
          $(this).css({
            'text-decoration':'underline',
            'font-family':'Gotham-Medium'
          }); 
      $("#menu3").mouseleave(function(){
          $(this).css({
            'text-decoration':'none',
            'font-family':'Gotham-Medium'
          }); 
      });
    }); 
</script>

Answer №1

Check out this functional demonstration. Here are some key points to take note of:

HTML

Consider assigning an ID to your menu for better organization. Using a generic class name like menu might lead to styling conflicts as you develop your website. Additionally, utilizing an anchor tag (<a>...</a>) instead of a div within the list (<li>...</li>) can simplify your structure.

    <nav id="menu">
        <ul>
          <li>MENU 1</li>
          <li>MENU 2</li>
          <li>MENU 3</li>
          <li>MENU 4</li>
        </ul>
    </nav>

CSS

Avoid using jQuery solely for implementing hover effects. Achieve the same outcome more efficiently with CSS. Here's how:

    #menu li {
      font-family: 'Gotham-Medium';
      cursor: pointer;
    }

    #menu li:hover {
      text-decoration: underline;
    }

jQuery

You can streamline your code by toggling visibility based on the clicked element's class. No need to duplicate code for each navigation item. Follow this approach:

      $("#menu li").on("click", function(e) {
        e.preventDefault();
        $("#menu li").hide();
        $(this).show();
      });

Answer №2

To create a hover effect, utilize CSS by using the :hover selector. Assign a class to all menu buttons and then target them using this class. Here is an example:

// HTML

<nav class="menu">
    <ul>
      <li><div class="menu-item" id="menu1">menu1</div></li>
      <li><div class="menu-item" id="menu2">menu2</div></li>
      <li><div class="menu-item" id="menu3">menu3</div></li>
      <li><div class="menu-item" id="menu4">menu4</div></li>
    </ul>
  </nav>

// CSS

.menu-item:hover {
  text-decoration: underline;
  cursor: pointer;
}

To display content on click, apply the same method used for adding CSS with jQuery. Use the this keyword. By adding a class to menu buttons, you can add an event listener and likewise hide all menu content with a common class. By following a pattern between menu button ids and content ids, a generic solution can be achieved.

$(".menu-item").click(function(){
    $(".menu-content").hide();
    $('#'+$(this).attr('id') + '-content').show();          
});

View a demonstration here: https://jsfiddle.net/etqwf3kr/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The issue of overflowing scroll functionality appears to be malfunctioning

.main-content{ height: 100%; width: 60%; min-height: 800px; background-color: white; border-radius: 5px; margin-left: 1%; border: solid 1px black; } .profile-banner{ display: flex; flex-direction: row; justify-content: space-between; ...

The individual HTML content does not appear in Fancybox; instead, it is displayed as part of a gallery

Facing an issue with a single HTML file not displaying in fancybox as expected. Instead of opening individually, it is appearing as part of a gallery with next and prev buttons. Is there a way to hide or disable these navigation buttons? ...

Discover the elusive tag that holds the specified text

My code snippet in HTML looks like this: <body> <div class="afds"> <span class="dfsdf">mytext</span> </div> <div class="sdf dzf"> <h1>some random text</h1> ...

Why is it impossible for me to delete the class / property of this object?

Within a series of nested divs, there are additional divs containing multiple imgs. The goal is to cycle through these images using CSS transitions. To achieve this, a JavaScript object was created to track the divs, sub-divs, and images. Three arrays were ...

Troubleshooting AngularJS stateProvider functionality issues

I am new to angularjs. I am not getting any errors or results in my testing project below. index.html <html ng-app="UserAuth"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> ...

Tips for adjusting the content direction of a Popover

I am currently working on a component that includes the following code: import { Popover, PopoverTrigger, PopoverContent, PopoverBody, Portal, Button, } from "@chakra-ui/react"; import { ReactNode } from "react"; import { Co ...

implementing a collapsible sidebar menu with CSS tables

I am working on a layout with three columns created using css tables to perfectly fit the browser window. The first column serves as a menu and I want it to hide or move to the left when clicked, allowing the middle column to expand into its space. However ...

Press the button to automatically scroll to a designated div section

One of the challenges I'm facing involves a fixed menu and content box (div) on a webpage. Whenever I click on the menu, the content box should scroll to a specific div. Initially, everything was working fine. Here is a sample of it in action: http ...

Button with opaque background over a see-through backdrop

I am having trouble making the button within a semi-transparent caption area over an image non-transparent. Any suggestions on how to achieve this? <div class="col-md-12 landing-container"> <img src="images/pig.jpg" class="main-imag ...

Having trouble spinning the picture using Reel in Reactjs

I have recently started learning React and I am attempting to use jQuery reel to rotate a list of images by 360 degrees. While I have successfully implemented this using purely jQuery, I now want to migrate it over to Reactjs. The issue arises when trying ...

Edit the settings for the dual-axis line chart's parameters

After countless hours of scouring the Internet and numerous attempts, I have come to the decision to seek help by posting my issue on this forum. I must confess, I am not the best developer. My approach usually involves finding pre-existing code that I ca ...

Achieving compatibility with IE7 for utilizing "before:" and "after:" pseudo-elements along with the "box-sizing:border

My website is constructed with twitter bootstrap 3 and functions perfectly on all browsers except for IE7. IE7 seems unable to interpret pseudo classes like before:, after:, and box-sizing: border-box. Is there a solution to make IE7 understand this code ...

CSS: Revert INPUT Element Back to Default Width

Although it may seem impossible, I am still going to ask the question. Suppose I have the following HTML: <div style="width: 500px;"> <input class="full" /> </div> And the corresponding CSS: input { width: 100%; } .full { ...

Keeping Ajax active while the PHP script is running is essential

Seeking assistance with a specific issue. I currently have an ajax script (index.php) that sends variables to a php file (thumbs.php). The php file generates thumbnail images from original files and saves them on the server. This process can sometime ...

The XORS error appears when using Angular $http, but $ajax from jQuery works fine

As the title suggests, I'm facing an issue with my code. The first part where I make a $http call is giving me a cross-domain error. However, the second part using jQuery ajax call works perfectly and returns an array of data. Can anyone shed some li ...

Creating a fresh JSON structure by utilizing an established one

I have a JSON data that contains sections and rubrics, but I only need the items for a new listing. The new object named 'items' should consist of an array of all the items. The final JSON output should be sorted by the attribute 'name&apos ...

Chrome browser CSS trapezoid shape clickability problem

I am attempting to make a trapezoidal perspective shape clickable for the entire area. It's currently working in Firefox and IE, but I'm encountering issues with Chrome. Here is a demonstration of the shape and a link: http://jsfiddle.net/9n9uh6 ...

In JQuery, an empty string will be returned if it contains the dollar sign character

In the scenario presented here, the value is retrieved accurately with the exception of when it includes a $ symbol at the beginning (e.g. $25.00), in which case it consistently results in an empty string. HTML: <input type="number" class="form-contro ...

The function socket.on(..) is not being triggered

Currently, I am in the process of developing a straightforward website to showcase socket communication and chat capabilities. The server side is coded using Python Flask app, while the client-side utilizes JavaScript. Below is an excerpt from the server c ...

What is the best way to differentiate between two calls to the same method that are based on different arguments?

Currently, I am utilizing sinon to mock functions from Google Drive in my NodeJS project. In a single test scenario, I make two separate calls to the create method (without the ability to restore between calls): // Call 1: drive.files.create({ 'reques ...