how to change visibility with Javascript

As I work on creating a menu using HTML and JavaScript, I've designed it to be a grid layout with 3 rows and 2 columns. The menu contents are also structured in a grid format. When the screen width is reduced, the layout changes to a single row and column. The concept is to have the menu contents hidden when the screen size decreases, with users needing to click on the heading to reveal the contents. To achieve this functionality, I've written a JavaScript code snippet. However, I encountered an issue where, upon expanding and collapsing the contents, they remain invisible when the screen width is increased again. Below is a portion of the code, and I'm seeking assistance on solving this problem.

const toggleElements = document.querySelectorAll('.toggle');

toggleElements.forEach(toggle => {
  const content = toggle.nextElementSibling;

  toggle.addEventListener('click', () => {
    if (content.style.display === 'none') {
      content.style.display = 'block';
    } else {
      content.style.display = 'none';
    }
  });
});
#assist {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  margin-top: 17px;
  white-space: nowrap;
  max-width: 1300px;
}

.toggle {
  font-size: 1.2rem;
}

.content {
  display: block;
  margin-top: 4px;
}

.content a {
  display: grid;
}

#assist .content {
  line-height: 35px;
  margin-bottom: 50px;
}

@media screen and (max-width: 1270px) {
  #assist {
    display: grid;
    grid-template-columns: repeat(1, 1fr);
  }
  #assist .content {
    display: none;
  }
}
<div id="assist">
  <div>
    <span class="toggle">Retun Policy</span>
    <div class="content">
      <a href="">What is the retun policy</a>
      <a href="">Test2 </a>
      <a href="">Test 3</a>
    </div>
  </div>
  <div>
    <span class="toggle">Corporate</span>
    <div class="content">
      <a href="">Where can I learn more about company</a>
      <a href="">Test2</a>
      <a href="">Test3</a>
    </div>
  </div>

Answer №1

The issue at hand is due to the fact that the content element has a style of display: none applied to it, which persists even as the screen size increases.

To resolve this, you can set up an event listener for the resize event and revert the styles. You can achieve this with the following code snippet:

const elementsToToggle = document.querySelectorAll('.toggle');

window.addEventListener('resize', () => {
    elementsToToggle.forEach((element) => {
        const info = element.nextElementSibling;

        if (window.innerWidth <= 1270) {
            // hide the info
        } else {
            // show the info
        }
    });
})

Answer №2

Let's get started!

@media (min-width: 1271px) {
  #assist .content {
    display: block!important;
  }
}

const toggleElements = document.querySelectorAll('.toggle');

toggleElements.forEach(toggle => {
  const content = toggle.nextElementSibling;


  toggle.addEventListener('click', () => {
    if (content.style.display === 'none') {
      content.style.display = 'block';
    } else {
      content.style.display = 'none';
    }
  });
});
#assist {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  margin-top: 17px;
  white-space: nowrap;
  max-width: 1300px;
}

.toggle {
  font-size: 1.2rem;
}

.content {
  display: block;
  margin-top: 4px;
}

.content a {
  display: grid;
}

#assist .content {
  line-height: 35px;
  margin-bottom: 50px;
}

@media screen and (max-width: 1270px) {
  #assist {
    display: grid;
    grid-template-columns: repeat(1, 1fr);
  }
  #assist .content {
    display: none;
  }
}

@media (min-width: 1271px) {
  #assist .content {
    display: block!important;
  }
}
<div id="assist">
  <div>
    <span class="toggle">Retun Policy</span>
    <div class="content">
      <a href="">What is the retun policy</a>
      <a href="">Test2 </a>
      <a href="">Test 3</a>
    </div>
  </div>
  <div>
    <span class="toggle">Corporate</span>
    <div class="content">
      <a href="">Where can I learn more about company</a>
      <a href="">Test2</a>
      <a href="">Test3</a>
    </div>
  </div>

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

What is the best method for eliminating the default title in selectpicker?

I'm currently working on integrating angular selectpicker into my project. Initially, everything was displaying correctly as shown below: <select class="selectpicker"> <option>Mustard</option> <option>Ketchup</opti ...

Having trouble getting the ValidatorPipe to function properly in my nest.js application

Issue Description There is an issue with the current behavior where initializing a validation pipe for a request body does not reject invalid types as expected. Desired Outcome The expected behavior should be that when a user provides a value that does n ...

How can you ensure that a row of content is accessible by making it clickable in a valid way?

I'm currently working on developing a widget that resembles a clickable bootstrap media object list that is easily accessible. https://getbootstrap.com/docs/4.3/components/media-object/#media-list The original code has the JavaScript click event attac ...

Implementing multiple content changes in a span using javascript

Having an issue with a pause button where the icon should change on click between play and pause icons. Initially, the first click successfully changes the icon from a play arrow to a pause icon, but it only changes once. It seems like the else part of the ...

Adding an active class to a link tag depending on the current URL and custom Vanity URLs - here's how!

I have a functioning code snippet, but it seems to be missing a crucial part when dealing with URLs such as www.mysite.com/home/. It works perfectly fine if the URL ends with index.aspx, like www.mysite.com/home/index.aspx, but fails when that part is omit ...

AngularJS: intercepting custom 404 errors - handling responses containing URLs

Within my application, I have implemented an interceptor to handle any HTTP response errors. Here is a snippet of how it looks: var response = function(response) { if(response.config.url.indexOf('?page=') > -1) { skipException = true; ...

Resolving Typescript custom path problem: module missing

While working on my TypeScript project with Express.js, I decided to customize the paths in my express tsconfig.json file. I followed this setup: https://i.stack.imgur.com/zhRpk.png Next, I proceeded to import my files using absolute custom paths without ...

Experiencing code coverage challenges in Angular 8 relating to function properties

https://i.sstatic.net/WQpVB.png Looking for suggestions on how to create a unit test case in Jasmine to address the code coverage problem. Any ideas? ...

Utilizing Ajax and Jquery to dynamically adjust CSS properties, dependent on data from a specific MySQL row

I've been working on a system to automatically update a Scene Selection page whenever a new number is added to the permission table in Mysql. The PHP for the login and retrieving the number from the members table is working fine. My issue now lies wi ...

How can JavaScript effectively retrieve the JPEG comment from a JPEG file?

How can one properly retrieve the JPEG comment field (not EXIF, but the COM field) from a JPEG file using JavaScript, particularly when running node on the command line? While there are several libraries available for reading EXIF data in JavaScript, I ha ...

Enhancing Your Website with Animation Delay using Animate.css and ViewportChecker

I am attempting to apply a delay to various elements with animated classes on a specific webpage using animate.css version 3.5.1 by Daniel Eden and jquery-viewport-checker version 1.8.7 by Dirk Groenen. My initial approach was to utilize the setTimeout fu ...

Retrieve information according to the currency specified

In my database, I have a table of tickets with prices listed in USD. If someone from a country outside the US wants to purchase a ticket, I'd like to display the prices in their local currency for better user experience. However, converting these pric ...

The issue I am facing is with the post_logout_redirect_uri not functioning properly when using localStorage in an OIDC Auth

authority: 'yyy', client_id: this.'yyy', redirect_uri: 'http://localhost:4200/login', response_type: 'token', scope: 'yyy', post_logout_redirect_uri: & ...

The paths of youngsters and the application of conditional styling

Here is the scenario I am dealing with: <div class="parent"> <div class"routeA"> <div class="header"> <li></li> <li class="p-highlight"></li& ...

Separate Your Navbar with Bootstrap 4 Separators

I'm facing a challenge in adding separators within a navigation bar between the navigation items. I am unsure how to evenly space out the padding on these separators next to each navigation item. https://i.sstatic.net/vjYti.png Another issue I encou ...

Toggle the sliding menu drawer option (upward/downward motion)

When it comes to my simple menu, I'm using jQuery to toggle the visibility of a few DIVs. The code is straightforward as shown below, and I could really use some assistance with adding extra functionalities. <div id="one" class="navLinks"> cont ...

Switch between displaying the HTML login and register forms by clicking a button

Currently, I am working on a website that requires users to either log in or register if they do not have an account. Below is the code I have developed for the login page: <span href="#" class="button" id="toggle-login">Log in</span> <di ...

Adjust background image size to fit the screen, not just the content

Whenever I set the background image for each page using the following JavaScript code, var imageUrl = 'url(' + imageUrl + ') top left no-repeat fixed'; $('body').css({ 'background': imageUrl }); I also add ...

In React using Flow Type, the syntax [...mySet] doesn't function as expected, while Array.from(mySet) successfully converts the

Why is it that with React and Flow Type, the line of code displaying [{}] when using JSON.stringify([...mySet]) but shows the correct values with JSON.stringify(Array.from(mySet))? The issue seems perplexing as this behavior cannot b ...