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

JavaScript is failing to execute the DELETE SQL transaction

I've been attempting to clear out my html5 local sql database, but for some reason, it's not working as expected. Below is the code I'm using, and no matter what I try, the alert always shows that the length is greater than 0. Any ideas why ...

Create a new instance of the TypeScript singleton for each unit test

I have a TypeScript singleton class structured like this: export default class MySingleton { private constructor({ prop1, prop2, ... }: MySingletonConfig) { this.prop1 = prop1 ?? 'defaultProp1'; this.prop2 = prop2; ...

Display images with sequential animation and a delay, combining fade-in and slide-up effects

I am attempting to create a cycling image display with specific effects: There should be a one-second delay before the first image is shown. The first image will appear with a fade-in and slide-up effect. Image #1 will remain visible for 5 seconds before ...

Working with CSS styles for the <datalist> element

I currently have a basic datalist drop-down menu and I am looking to customize the CSS to match the style of other fields on my website. However, as someone new to web design, I am unsure of how to go about this process. Check out the code here: http://j ...

What is the reason behind using angle brackets to access the initial value of an array with a variable inside?

I've been experimenting with this technique several times, but I still can't quite grasp why it works and haven't been able to find an answer. Can someone please explain? let myArray = [0, 1] let [myVar] = myArray console.log(myVar) // outpu ...

Display One Div at a Time in Sequence on Page Load Using jQuery

I have come across this question multiple times: How to Fade In images on page load using JavaScript one after the other? Fade in divs sequentially Using jQuery .fadeIn() on page load? Despite trying various recommended methods, I'm still unable t ...

ERROR: Module 're2' not found in './build/Release/re2' (npm)

After receiving suggestions from sonarQube, I am attempting to switch out my original regular expression with RE2. However, upon installation, the following error message appears: Error: Cannot locate module './build/Release/re2' Important note ...

JavaScript functions smoothly on Google Chrome but is restricted on Internet Explorer

Experimenting with the code found on this website to conduct some testing. The javascript functions smoothly in Google Chrome and Firefox, but encounters issues in IE. Interestingly, when I run the html file in IE locally, it does work, but a warning pops ...

Choose the Enum in a dynamic manner

I have three enums Country_INDIA, Country_USA,Country_AUSTRALIA. During runtime, the specific country name is determined (it could be either INDIA, USA, or AUSTRALIA). Is it possible to select the correct enum based on the country name at runtime? For in ...

How can we stop a form from being submitted when the input field is

Similar Question: How to prevent submitting the HTML form’s input field value if it empty <?php include '../core/init.php'; if(isset($_POST['nt']) && isset($_POST['ntb'])){ mysql_query("INSERT INTO `pos ...

Tips for automatically closing the Toggle Navigation feature in Vue JS when a user clicks outside of the navigation container

Is there a way to close the toggled navigation menu automatically when the user clicks outside of the navigation container? I have implemented two ul menus inside the navigation menu and would like the subNavActive, safNavAcitve, and repNavUl variables to ...

An object-c alternative to encodeURIComponent

Having difficulty finding information on this through a search engine. Is there a similar method in Objective-C for encoding URI components? http://www.w3schools.com/jsref/jsref_encodeuricomponent.asp This is a common task, but I am unable to locate any ...

Issue with CSS: 200vw not scaling correctly for mobile devices

I'm attempting to create a horizontal slide effect between two div elements, so here is the HTML code: <div id="container"> <div class="viewport-1"> <div class="inner-div"> <h1>Viewport background 1</h1></ ...

How can I retrieve a variable in a JavaScript AJAX POST request?

Similar Question: How to retrieve a variable set during an Ajax request I am facing a challenge, as I am making an ajax call and receiving a number as the response. My query is, how can I assign this returned number to a variable that is accessible ou ...

The slice() method in arrays provides a reference to the elements rather than copying

In my file, I am exporting an object in the following manner: export const LINECHART2_DATA = { series: [{ data: [], name: 'HR', }, { etc... }] } The way I import it is like this: import { LINECHART2_DAT ...

My Bootstrap navbar seems to be malfunctioning. I'm wondering if there could be an issue with

here is a snippet of the code I'm working on: <nav class="navbar navbar-expand-md navbar-dark bg-dark sticky-top"> <div class="container-fluid"> <a class="navbar-brand" href="#"> <img src="https://i.stack.imgur.com/5XeYV.png" ...

Generating HTML widgets dynamically with jQuery: A step-by-step guide

Looking for a way to display an interactive widget on your page while allowing users to generate multiple instances and interact with them simultaneously? Imagine having a widget like this: <div id="my_widget"> <script type="text/javascript" ...

The image fails to load once the AI-generated image is complete and the response process has concluded

After a long hiatus from development, I am diving back in and acknowledging the rustiness of my skills. Any syntax or formatting errors encountered are preemptively apologized for. Currently, I am immersed in a small web app project that involves taking a ...

Leverage the power of Angular and Node.js to dynamically generate and configure a new subdomain on an

Currently, I am tackling a project that involves generating sub domains dynamically based on the prefixes entered by users on my website. While everything is functioning properly on my localhost using diet.js and express-subdomain, errors are being encount ...

Use Vue.js class bindings to create blank spaces in between CSS classes

I'm utilizing a v-bind:class binding on a component in order to toggle a css class based on the truthiness of a boolean within my Vue.js component. When I specify this in my template: <aside v-bind:class="{'--opened': sidebarVisible}" ...