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:

Users are able to click on various menu items to access different content.

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

Looking for an API to retrieve random quotes and images from a website?

Greetings, my name is Antika. I recently embarked on a coding journey and have been focusing on learning HTML/CSS along with the basics of JS. Level of Expertise: Beginner During my exploration, I stumbled upon this intriguing website - . It stands out a ...

Understanding the response from an AJAX call

VB code Dim temp3 As String = dt.ToString() cmd.Connection = con con.Open() i = cmd.ExecuteNonQuery() con.Close() If i = 1 Then msg = "Record successfully inserted" ...

How can I modify the style of a cell in jqgrid when the mouse hovers over it?

I need to change the class of cells in the first column of my grid. Currently, I set them using this code: $("#myGrid").jqGrid('setCell',rowid,'column_1', '', '**ui-state-default**'); Is there a way to modify the c ...

The updating of input and output does not happen instantly; there is a delay before changes

Having an issue with updating input values in React. When using the setState method, the console log does not show the updated input value immediately. For instance, typing "a n" into the input only logs "a" after the second keystroke... Although I under ...

What is the method for retrieving the name of a canceled file?

When a user clicks on the "Cancel" button during an upload, I am attempting to retrieve the filename of the file that was canceled. However, it seems like the current method I am using (var image_file_name) is not successfully retrieving the name of the ca ...

Distinguishing between selecting rows and selecting checkboxes in Mui Data Grid

Is there a way to differentiate between clicking on a row and clicking on the checkboxes? I want to be able to select multiple rows by clicking anywhere in the row except for the checkbox column. When clicking outside the checkbox column, I would like to p ...

Simply output the integer value

Recently, I've been working on a function that I'm trying to condense into a one-liner code for a challenge on Codewars. You can find the problem here. Here's the code snippet that I currently have: export class G964 { public static dig ...

What is the best way to seamlessly transition layers from one location to another as the mouse exits and re-enters the window?

I have been working on refining a parallax effect to achieve a seamless transition between two positions based on where the mouse exits and enters the window. In the JSFiddle example provided, there is a slight 'pop' that I am looking to replace ...

Is it possible to use a server action in Next.js to both retrieve data and refresh the page?

I am currently working on developing a web application using Next.js (13.4.9) and I intend to utilize server actions. These server actions will involve sending data to the server, which will process the data and return a string back to me. The challenge I& ...

Error message in React Js indicating the absence of a specified file or directory: "Package.json cannot

When I try to run npm start, I encounter the following error - PS D:\React\operations_app_tut> npm start npm ERR! path D:\React\operations_app_tut\package.json npm ERR! code ENOENT npm ERR! errno -4058 npm ERR! syscall open npm ...

Steps for setting up an info window on a Google map with multiple markers

I'm having trouble getting the infowindow to pop up on the multiple custom markers I added using AJAX on Google Maps. Everything was working fine before I tried implementing the infowindow and adding the listenMarker() function. The icons were in the ...

Transferring JSON data using $.post in Express/NodeJS

Below is the contents of my app.js file: var express = require('express'); var app = express(); var path = require('path'); var $ = require('jquery'); var nodemailer = require('nodemailer'); app.use('/static&a ...

Show the button only when the text is updated

Is there a way to display a button only when the quantity of items in the cart changes, similar to the eBay shopping cart feature? I was able to implement it but it's not functioning as expected. Here is the link to what I have so far. Does anyone kno ...

What is the best way to utilize jQuery in order to present additional options within a form?

Let's consider a scenario where you have an HTML form: <form> <select name="vehicles"> <option value="all">All Vehicles</option> <option value="car1">Car 1</option> <option value="car2">Car 2< ...

Dealing with the error "Type 'date[]' is not assignable to type '[date?, date?]' in a React hook

I'm attempting to assign a date range but encountering an error that states: Type 'Date[]' is not assignable to type '[Date?, Date?]'. Types of property 'length' are incompatible. Type 'number' is not assignab ...

The lack of vertical alignment in the table

Trying to do something really simple here and I'm a bit stuck. Currently working on a forum project, and surprisingly the backend is error-free (thanks to some questionable magic tricks), However, my current task is to display all subcategories using ...

The search filter in react material-table is not functioning properly upon initialization

Search functionality is functioning correctly in this code snippet: <MaterialTable columns={[ { title: 'Name', field: 'firstname', type: 'string' } ]} /> Unfortunately, the Search filte ...

A JavaScript async function that can be activated either by clicking the search button or by hitting the "enter" key in the input field

Recently, I've been working on an async function in Vanilla Javascript that is triggered by a click event on the search button. However, I would like to modify it so that the function can also be initiated when the "enter" key on the keyboard is press ...

Complete and automatically submit a form in a view using AngularJS

I have developed a basic AngularJS application that is functioning smoothly. Currently, I am looking to populate certain fields and submit the form directly from the view without requiring any user input. Below, you'll find some simplified JavaScrip ...

Interact with the database using jQuery Ajax in Rails 3

Currently, I am in the process of developing an estimate form that can accommodate multiple line items. Once a line item is completed by inputting data for the following fields: properties height letter_quantity The goal is to fetch a unit price from a ...