Hide the previous dropdown content in Vue JS by manipulating the visibility of the elements

I'm currently working on creating a Dropdown feature, but I'm facing an issue with hiding the dropdown content when another dropdown is clicked.

<template>
  <div class="dropdown-container">
    <div
      v-for="(item, index) in dropdownItems"
      :key="index"
      @click="toggleDropdownContent(item)"
      class="dropdown"
    >
      <div class="dropdown-title">
        <p>{{ item.text }}</p>
        <div v-show="item.show">
          <p>{{ item.content }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  methods: {
    toggleDropdownContent(item) {
      this.dropdownItems.forEach(element => {
        if(element !== item) {
          element.show = false;
        }
      });
      item.show = !item.show;
    },
  },
  data() {
    return {
      dropdownItems: [
        {
          text: "What is Lorem Ipsum?",
          content:
            "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots ",
          show: false,
        },
        {
          text: "Where can I get some?",
          content:
            "There are many variations of passages of Lorem Ipsum available, but",
          show: false,
        },
      ],
    };
  },
};
</script>

Currently, the dropdown menu opens when a text is clicked, but the issue arises when clicking on a different text, as the old menu does not close. I'm looking for a solution where the old menu closes when a new one is clicked.

Answer №1

To ensure only one dropdown is visible at a time, modify the showContent() method to hide all other dropdowns except the current one. Instead of using i, pass the current index as a parameter:

<div
  v-for="(i, index) in contentInfo"
  :key="index"
  @click="showContent(index)"
  class="dropdown"
>

Update the showContent method:

showContent(currentIndex) {
  this.contentInfo.forEach((entry, index) => {
    // Toggle current dropdown
    if (index === currentIndex) {
      entry.show = !entry.show;
    } else {
      // Hide all other dropdowns
      entry.show = false;
    }
  });
}

For a more concise version, you can condense it into a one-liner:

showContent(currentIndex) {
    this.contentInfo.forEach((entry, index) => entry.show = (index === currentIndex ? !entry.show : false));
}

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

Is it possible to receive a unique value error even when providing the correct key value in a map?

I encountered an issue while using a map function with an array in my application. Even though I have provided a unique key, Google Chrome console is still showing an error related to the unique key. Error Each child in a list should have a unique "ke ...

Tips for implementing a ternary operator within a component using the v-for directive

Here is the updated code with a conditional check for item.image: <template lang="pug"> b-carousel.d-none.d-sm-block( id='categoryRoulette' controls no-animation :interval='0' ) b-carousel-slide( v-for=&quo ...

Discover a method to receive an alert when the mouse exits the inner window along the y-axis

Is there a way to receive an alert if the mouse moves out of the inner window solely in the y-axis? Currently, alerts are triggered when the mouse moves out on both x-axis and y-axis. For example, if the mouse pointer hovers over the address bar coming fro ...

Challenges encountered when uploading files

Within my react form, I have multiple files that are uploaded to be sent to the backend. Below is a snippet of code for the form submit button: const handleSubmit = async (e) => { e.preventDefault(); setDisabled(true); const ...

Automatically resizing font to fit the space available

I am attempting to achieve the task described in the title. I have learned that font-size can be set as a percentage. Naturally, I assumed that setting font-size: 100%; would work, but unfortunately it did not. For reference, here is an example: http://js ...

Converting keyValue format into an Array in Angular using Typescript

Is there a way to change the key-value pair format into an array? I have received data in the following format and need to convert it into an array within a .TS file. countryNew: { IN: 159201 BD: 82500 PK: 14237 UA: 486 RU: 9825 } This needs to be transf ...

Is there a way to create a header that fades out or disappears when scrolling down and reappears when scrolling up?

After spending some time researching and following tutorials, I have not made much progress with my goal. The task at hand is to hide the top header of my website when the user scrolls down and then make it reappear when they scroll back up to the top of t ...

Using Vue to create a component that binds an array as its data source

Having trouble binding an array as a variable and accessing it in the child component, resulting in the variable being undefined. Is there a way to pass an array from a view to a component so that the component can use this array to create a child componen ...

Compiling Vue with TypeScript: Troubleshooting common errors

Using Vue Components with Templates Multiple Times in TypeScript I am working on utilizing a component with a template multiple times within another component. The code is split between a .html file and a .ts file. The .html file structure is as follows: ...

How can I show a legend entry for every column in Amcharts?

Take a look at this code snippet: http://jsfiddle.net/ouLed1fp/ How can I create a legend entry for each column in the chart? Also, is there a way to display the column names next to them, providing a clear legend? <div id="chartdiv" style="width: 10 ...

What are the steps to effectively utilize <ul> for showcasing scrolling content?

I stumbled upon and found it to be a great inspiration for my project. I tried replicating the layout of the listed items on the site: .wrap { display: block; list-style: none; position: relative; padding: 0; margin: 0; border: ...

Tips on extracting information from several JSON response objects

I have the following ArrayList: JSONArray JMyDataList= new JSONArray(MyDataList); JSONArray JMyProjectData = new JSONArray(MyProjectData); MyDataList: contains data retrieved from a database with column names and data. response.setConten ...

Utilizing $.when to merge AJAX requests and then passing the resulting data to a designated function

I am struggling with sending data between functions and using $.when in my JavaScript code. I have separate functions and AJAX calls that update content on the page, but they need to load together on page load. Despite trying various solutions to combine A ...

Choose a particular character in a text that corresponds with a regular expression in Javascript

I am looking to replace the symbols < and > within the text. I have constructed a regular expression as follows: (<span[^>]+class\s*=\s*("|')subValue\2[^>]*>)[^<]*(<\/span>)|(<br(\/*)>) This ...

visit a new page with each reload

Can I navigate to a new page without refreshing the current window.location.href? I attempted to achieve this using a jQuery event handler on the window object, however, it doesn't seem to be functioning properly. $(window).on('reload', fu ...

Exploring the concept of 'mapping' in jQuery: A guide to traversing an array with varying variable values

I need assistance in linking two unrelated data points together. I have an array that stores images at specific positions, and a variable that can hold different values (1, 2, or 3). My goal is to connect the array position (1, 2, or 3) with the variable v ...

I am having trouble with my scroll reveal effects on JavaScript, how can I troubleshoot and fix the issue?

I'm currently making updates to my portfolio website, but for some reason, the scroll reveal animation has suddenly stopped working. I made a few edits and now it seems to be broken. /*===== SCROLL REVEAL ANIMATION =====*/ const sr = ScrollReveal({ ...

Having trouble sending form data using the jQuery AJAX POST method?

I am facing an issue with a simple form that is supposed to send data to PHP via AJAX. However, when I submit the form, the data does not get sent across. Here is the JavaScript code: $(document).ready(function(e) { $('#update').submit(func ...

jQuery condition doesn't properly resetting the states of the original checkboxes

Having trouble phrasing the question, apologies! Take a look at this fiddle to see my objective: http://jsfiddle.net/SzQwh/. Essentially, when a user checks checkboxes, they should add up to 45 and the remaining checkboxes should then be disabled. The pr ...

Tips for initiating a function at a designated scroll point on a webpage

Currently, I am testing out a code snippet that allows images to flip through in a canvas element. I'm curious if it's possible to delay the image flipping effect until the viewer scrolls down to a specific section of the page where the canvas i ...