Clicking on the menu to reveal the dropdown options using JavaScript

I have created a drop-down menu for my website, but I am facing an issue. When I click on the links again, it does not work properly because I lack expertise in JavaScript. I would appreciate any help and suggestions from all of you. Thank you for your time.

Below is the code I have used:

    var hideall = $('#woman,#man,#device,#health,#living,#device');

    $('#woman-li').click(function() {
      $(hideall).hide(), $('#woman').show();
    });


    $("#man-li").click(function() {
      $(hideall).hide(), $('#man').show();
    });


    $("#health-li").click(function() {
      $(hideall).hide(), $('#health').show();
    });
    #woman,
    #man,
    #health,
    #device,
    #living {
      display: none;

    }
<div id='cssmenu'>
  <ul>
    <li class='active'><a href='#'><span>Home</span></a>
    </li>
    <li>
      <a href="#"> <span id="woman-li">Woman</span> 
      </a>
    </li>
    <li>
      <a href="#"> <span id="man-li">Man</span> 
      </a>
    </li>
    <li>
      <a href="#"> <span id="health-li">Health</span> 
      </a>
    </li>
  </ul>


  <div id='woman'>

    <div class="tb-container">
      <div class="tb-head">face</div>
      <div class="tb-content">
        <a href="#">
          <p>face</p>
        </a>
      </div>
    </div>
  </div>

  <div id='man'>

    <div class="tb-container">
      <div class="tb-head">face</div>
      <div class="tb-content">
        <a href="#">
          <p>face</p>
        </a>
      </div>
    </div>
  </div>

  <div id='health'>

    <div class="tb-container">
      <div class="tb-head">face</div>
      <div class="tb-content">
        <a href="#">
          <p>face</p>
        </a>
      </div>
    </div>
  </div>

Answer №1

In my personal experience, using list items and implementing an onclick handler to navigate to a specific page is a more organized approach for styling purposes. If this method interests you, check out the following link: https://jsfiddle.net/Domination/erdhvjvm/7/

Here's the layout:

<div id='cssmenu'>
    <ul>
        <li id='home' class='active'>Home
            <div>Face</div>
        </li>
        <li id='woman'>Woman
            <div>Face</div>
        </li>
        <li id='man'>Man
            <div>Face</div>
        </li>
        <li id='health'>Health
            <div>Face</div>
        </li>
    </ul>
</div>

Custom styles applied through CSS:

#cssmenu ul{
    border-top:1px solid black;
    padding:0;
}
#cssmenu li{
    background:red;
    border:1px solid black;
    border-top:0;
    cursor:pointer;
    list-style-type:none;
    padding:0.5em;
}
#cssmenu li.active{
    background:green;
}
#cssmenu div{
    margin-left:15px;
}

Javascript functionality:

//Initially hides all dropdowns
$('#cssmenu ul li div').hide();

//Handles click events on list items
$('#cssmenu ul li').click(function(e){
    if (e.target == this){ 

        $('#cssmenu ul li div').stop(); 

        $(this).siblings().find('div').slideUp(); 

        $(this).siblings().removeClass('active'); 

        $(this).find('div').slideToggle();

        $(this).addClass('active');
    }
});

//Click event handling for submenu clicks
$('#cssmenu ul li div').click (function(){
    alert("You clicked on a child");
    alert("Navigate to: " + $(this).attr('link'))

    //Uncomment to enable navigation
    //window.location.href = $(this).attr('link');
})

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

Navigate to the following fieldset using jQuery modal after receiving a response code through AJAX

I have a GET AJAX call being sent to Mailchimp from a JQuery modal using the following scripts. How can I automatically navigate the user to the next fieldset if the server response is successful? Should this be done in the initial JavaScript or in the PHP ...

Adjust the jQuery.ScrollTo plugin to smoothly scroll an element to the middle of the page both vertically and horizontally, or towards the center as much as possible

Visit this link for more information Have you noticed that when scrolling to an element positioned to the left of your current scroll position, only half of the element is visible? It would be ideal if the entire element could be visible and even centere ...

Issue: Invalid element type - Error message displayed when attempting to show the Edit button

I am currently learning about React and trying to implement an edit button next to the rows for editing data in the database. However, I keep encountering this specific error message: Error: Element type is invalid: expected a string (for built-in compone ...

Exploring jasmine-node: unraveling the mysteries of errors

As I embark on my journey to learn JavaScript, I decided to tackle some exercises on exercism.io. This platform provides pre-written tests that need to be passed. While things were going smoothly initially, I hit a roadblock with the latest exercise where ...

Property usedJSHeapSize in Chrome

After doing some research online, I found that the documentation on this topic is quite lacking. I am currently dealing with a significant memory leak in my code and have been using: window.performance.memory.usedJSHeapSize However, it seems like the val ...

Using jQuery to locate a JavaScript variable is a common practice in web development

I recently created a JSFiddle with buttons. As part of my journey to learn jQuery, I have been converting old JavaScript fiddles into jQuery implementations. However, I seem to be facing a challenge when it comes to converting the way JavaScript fetches an ...

When a page first loads in Next.js with Firebase, the useEffect hook may return an undefined value

My component is designed to retrieve a subcollection from firestore: import { useEffect, useState } from "react"; import { db } from '../firebase/firebaseInit' import {useAuth} from '../components/AuthContextProvider' import { ...

What is the best way to make the div inside the table cells expand to fill the available space?

I'm having trouble making the inner divs within table cell divs expand and fit their parent div without overlapping the next cell below it. Check out the sandbox for reference I've outlined the areas in grey where I want the cells to be filled. ...

What is the method for sending a file using JavaScript?

var photo = 'http://cs323230.vk.me/u172317140/d_5828c26f.jpg'; var upload_url = 'http://cs9458.vk.com/upload.php?act=do_add&mid=62..'; var xmlhttp = getXmlHttp(); var params = 'photo=' + encodeURIComponent(photo); xmlhttp ...

Tips for adjusting HighCharts layout with highcharts-vue integrations

I have a fairly simple component: <template> <div> <chart v-if="!loading" ref="priceGraph" constructor-type="stockChart" :options="chartData" ...

Revamp the website to create a more streamlined and compact version that mirrors the functionality of the desktop website

My goal is to make my website responsive on all mobile devices. I want the mobile version to look exactly like the desktop version, just smaller in size. I attempted using transform but it didn't have the desired effect. I aim to achieve the same con ...

Utilizing variable query operators solely in instances where they hold value

Imagine you are on a movie website where you can customize filters for the movies displayed to you. Currently, these preferences are stored in the User model as a map. Here is an example of what the preferences object might look like: preferences: { yea ...

Delete JavaScript functions and events from memory once the JavaScript code has been removed from the HTML file

I am encountering a situation with my website where popups loaded via ajax also load JavaScript code, which I want to remove when the popup is closed. The main site code looks like this: <body> ... <div id="popup" style="display:none"> < ...

Troubleshoot your Vue.js application using Visual Studio Code. Encounter an unidentified breakpoint error

I'm encountering a problem with debugging my Vue.js project using VS Code and Chrome. I followed the official guide on the website Guide, but it's not working for me. The error I keep running into is: unverified breakpoint What am I doing wrong? ...

How to retrieve all the text inside an element using Protractor and Selenium

<div class="test"> <span> <div>CONTENT </div> </span> <div> <ul> <li> <span>More text</span> EXAMPLE1</li> <li>EXAMPLE2</li> ...

What could be causing Vuejs to not update elements promptly?

Currently, I am encountering a scenario where I am adding options to a select element using Vue.js when the @change event of that specific element is triggered. An issue arises where the new option is not 'registered' until I exit the function. ...

Discovering the magic of activating a JavaScript function on jQuery hover

I need to call a JavaScript function when hovering over an li element. var Divhtml='<div>hover</div>'; $('li a').hover(function(){ $(this).html(Divhtml); //I want to trigger hovercall(); wh ...

The $http function in AngularJS consistently returns undefined instead of the expected value

var result = dataService.makeHttpRequest("GET", "/documents/checkfilename/", null, function (response, status, headers, config) { // I can see `true` if I alert(response); here // I want to return the contents of ...

Incorporating a header include on every page throughout my website

Is there a way to include headers and footers in your HTML web pages without having to duplicate code on every page? I understand that this can be done using PHP, but what if you are creating a website solely with HTML? If there is no solution to avoid r ...

Utilizing an Ajax request for a polling system

I am in need of adding a polling mechanism to call a web service from my webpage. To achieve this, I am attempting to utilize an ajax call within a javascript page. However, I am fairly new to both ajax and javascript. Below is the code snippet that I have ...