When clicked, the menu disappears successfully with the "show" functionality, but unfortunately, the "hide" feature is not working as intended

Within my menu, I have a section for portfolios that transforms into a dropdown on desktop hover and mobile click. The issue arises on mobile devices where the first click displays the menu correctly, but subsequent clicks do not trigger any change.

I attempted to use .toggle() and .toggleClass(), yet neither approach produced the desired outcome. Currently, I am experimenting with an if/else statement in the JavaScript provided below. Essentially, it checks if the window width is less than 940px and then toggles the visibility of the menu on click of the parent element.

Edit:

For testing purposes, I am only conducting these tests on browser windows narrower than 940px to simulate a mobile experience.

Edit #2:

I have omitted the "if window width < 940px" condition from this question, as it might simplify responses at this stage.

$(function() {
  
  if ($('.nav__portfolio ul').css('visibility', 'hidden') == true) {
    $('.nav__portfolio').on('click', function() {
      $('.nav__portfolio ul').css('visibility', 'visible');
    });

  } else {
    $('.nav__portfolio').on('click', function() {
      $('.nav__portfolio ul').css('visibility', 'hidden');
    });
  }
  
};
.nav__portfolio ul {
  visibility: hidden;
<li class="nav__portfolio"><p>PORTFOLIO</p>
  <ul>
    <li>Dropdown Item</li>
    <li>Dropdown Item</li>
    <li>Dropdown Item</li>
  </ul>
</li>

Answer №1

It seems like the main issue lies in the condition you are using in the if statement:

  • $('.nav__portfolio ul').css('visibility', 'hidden')
    doesn't evaluate to true or false as it's not a boolean value

To fix this, you can compare the actual value of the css property like so:

$('button').on('click', function() {
  if ($('div').css('visibility') !== 'hidden') {
    $('div').css('visibility', 'hidden');
  } else {
    $('div').css('visibility', 'visible');
  }
})
div {
  height: 200px;
  margin: 20px 0;
  background: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button>Toggle the div</button>
<div></div>


The corrected logic for your code would look something like this:

$('.nav__portfolio').on('click', function() {
  if ($('.nav__portfolio ul').css('visibility') == 'hidden') {
    $('.nav__portfolio ul').css('visibility', 'visible');
  } else {
    $('.nav__portfolio ul').css('visibility', 'hidden');
  }
})

Answer №2

Have you considered using hasClass/addClass/removeClass as an alternative?

You might only require one click listener for this functionality.

if ($(window).width() <= 940) {

    $('.nav__portfolio').on('click', function() {
        if ($('.nav__portfolio ul').hasClass('visibleClass') {
            $('.nav__portfolio ul').removeClass('visibleClass');
        } else {
            $('.nav__portfolio ul').addClass('visibleClass');
        }
    });
}

.nav__portfolio ul {
    visibility: hidden;
}

.nav__portfolio ul.visibleClass {
    visibility: visible;
}

Answer №3

Using the toggle() method:

$('.nav__portfolio').on('click', function() {
   $('.nav__portfolio ul').toggle();
})
.nav__portfolio ul {
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li class="nav__portfolio"><p>PORTFOLIO</p>
  <ul>
    <li>Dropdown Item</li>
    <li>Dropdown Item</li>
    <li>Dropdown Item</li>
  </ul>
</li>

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

Steps to fix the issue: Unhandled Type Error: t.addLayer is not a recognized function

I've encountered a bit of difficulty with an error that I can't seem to figure out. I'm currently working on adding a geoJSON layer to my Leaflet Map, specifically a multi-polygon representing country borders. To achieve this, I'm using ...

What is the process for implementing optional chaining on a JSON object?

I'm currently facing an issue where I need to compare a value within a JSON object with a variable. if (resp.userdetails.name == username) { // do something } The challenge arises when not all resp objects contain the userdetails property, resulting ...

Audio playback system in Node.js

I'm looking to create a seamless playlist of mp3 files that play one after the other. While it may seem straightforward, I'm facing challenges keeping the decoder and speaker channel open to stream new mp3 data in once a song finishes playing. Be ...

Stop the stream coming from getUserMedia

After successfully channeling the stream from getUserMedia to a <video> element on the HTML page, I am able to view the video in that element. However, I have encountered an issue where if I pause the video using the controls on the video element a ...

What is causing the resistance in changing the color of my current navigation items?

I've encountered a small challenge with my header section. Despite multiple attempts, I'm struggling to change the color of the 'current' menu item. It seems that overriding Bootstrap's default color is proving to be more difficult ...

How can I include a path prefix to globs provided to gulp.src?

Consider the contents of these two essential files: settings.json { "importFiles": [ "imports/data.js", "imports/functions.js", "imports/styles.css" ] } builder.js var build = require("builder"), combine = require("combine-files"), ...

Securely Saving JWT Tokens from Auth0 Login in Node.js Express

As a novice in the world of Auth0, I am currently working on integrating it into my regular express web application. My main goal is to secure and validate users before they are able to access certain endpoints. From what I have gathered, this can be achie ...

Methods for dynamically adjusting content based on window width in Three.js

Currently, I have implemented a basic window resizing code in my project: function onWindowResize() { windowHalfX = window.innerWidth / 2; windowHalfY = window.innerHeight / 2; camera.aspect = window.innerWidth / window.innerHeight; came ...

What is the best way to display the user login in the center of a page with all necessary controls

Challenge How can the user login be displayed in the center of the page? Additional Information The current layout displays user login data on the left-hand side. I am looking to have the user login data centralized on the page, which includes labels f ...

Implementing real-time style changes with Angular 6 through Environment Variables

Attempting to dynamically change styles in Angular 6 using environment variables has been a success for me. Here is how my file structure is organized: src -app -assets -environments -scss -theme1.scss -theme2.scss -_variables.scss -styles.sc ...

Navigating through SlidesJS with a keyboard using jQuery

On my website, I have integrated SlidesJS to create a dynamic photo slideshow. One thing I'm struggling with is enabling keyboard navigation for the slideshow. I attempted to implement a solution from GitHub by adding code to my head tag (lines 94-1 ...

Array data causes tabs to be shown incorrectly

My attempt to create tabs similar to those in this tutorial has hit a snag. While I can easily display hard coded tabs, I'm facing issues when trying to populate the tabs from a list as they end up being displayed incorrectly. Here is the code and im ...

How can I retrieve an array from the server side using AngularJS?

Currently, I'm involved in developing a web application meant for team collaboration. While the login and signup pages have been set up, other members of my team are focusing on the server (built with node.js and express framework) and database aspect ...

css - targeting the last child element using a type selector

I'm attempting to target the final child element of type <div> within the container "#myDiv" <div id="myDiv"> <div> <img> <div> <div>text</div> ...

send a message to all clients using socket.io

I am having trouble figuring out how to broadcast a message from the client or another NodeJS file to all clients. While I was able to send messages to the server successfully, I am not able to reach every other client. Server code: var io = require(&ap ...

Can you explain the purpose of the behavior: url(); property in CSS?

While browsing the web, I came across a CSS property that caught my eye. It's called behavior, and it looks like this: #element{ behavior: url(something.htc); } I've never used or seen this property before. It seems to be related to Internet ...

How to perfectly align a full-width div with a div of specific width

Consider this scenario: .d1 { width: 100px; float: left; } .d2 { width: auto; float: left; } <div class="d1">Fixed Content</div> <div class="d2">This content should expand to fill the rest of the page vertically.</div> This setu ...

Is there a way to connect either of two distinct values in Angular?

Looking to assign the data with two possible values, depending on its existence. For instance, if I have a collection of TVs and I want to save the "name" value of myTVs[0] and myTVs[1]. For example: var myTVs = [ { "JapaneseTV": { ...

Removing a row from a table in a React component

I have incorporated a Table component from Material UI into my project to display data fetched from an external API. The table dynamically updates its rows based on events received through a web socket connection. One specific requirement I have is that wh ...

Adding text chips to a text field in Vuetify - A simple guide

I have successfully integrated a text field with vuetify and now I am looking to incorporate chips into it. Currently, chips are only added if the entered text matches a specific pattern (such as starting with '{' and ending with '}'). ...