Toggle visibility of div elements in a list

Users have the option to either download a file by clicking on "download" or view it as a PNG in their browser by clicking "open".

I found a solution on this platform for creating a show/hide toggle function. It worked well for one item, but I'm looking for a way to apply it to a list of 30 entries without duplicating code. Being new to web development, I'm unsure if there's a simpler solution that I'm missing.

Each entry should trigger its own div toggle when clicked on to open.

$('.list-link').click(function() {
  $('.test-div').show(500);
  $('.list-link').hide(0);
  $('.Hide').show(0);
});

$('.Hide').click(function() {
  $('.test-div').hide(500);
  $('.list-link').show(0);
  $('.Hide').hide(0);
});
.list-entry {
  background-color: darkgrey;
  width: 200px;
  margin-bottom: 10px;
  list-style: none;
}

.test-div {
  width: 200px;
  height: 100px;
  background-color: blue;
  display: none;
}

.Hide {
  display: none;
}
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>

<ul class="list">
  <li class="list-entry">
    <p> test 1</p>
    <div class="links">
      <a class="download-link" href="">download</a>
      <a class="list-link">open</a>
      <a class="Hide">hide</a>
  </li>
  <div class="test-div"></div>
  <li class="list-entry">
    <p> test 2</p>
    <div class="links">
      <a class="download-link" href="">download</a>
      <a class="list-link">open</a>
      <a class="Hide">hide</a>
    </div>
  </li>
  <div class="test-div"></div>
  <li class="list-entry">
    <p> test 3</p>
    <div class="links">
      <a class="download-link" href="">download</a>
      <a class="list-link">open</a>
      <a class="Hide">hide</a>
    </div>
  </li>
  <div class="test-div"></div>
</ul>

CodePen Link Here

Appreciate any help in advance!

Answer №1

If you want to achieve your goal, you can utilize jQuery's DOM traversal functions like closest() and find() to establish a connection between the element triggering the click event and its surrounding elements that you intend to modify.

It's important to recognize that your HTML is not valid. The ul element should only contain li elements, not div. Therefore, you need to adjust the layout slightly.

Here is a revised version of the code with these points in mind:

$('.list-link').click(function() {
  let $li = $(this).closest('li');
  $li.find('.test-div').show(500);
  $li.find('.list-link').hide();
  $li.find('.Hide').show();
});

$('.Hide').click(function() {
  let $li = $(this).closest('li');
  $li.find('.test-div').hide(500);
  $li.find('.list-link').show();
  $li.find('.Hide').hide();
});
.list-entry {
  background-color: darkgrey;
  width: 200px;
  margin-bottom: 10px;
  list-style: none;
}

.test-div {
  width: 200px;
  height: 100px;
  background-color: blue;
  display: none;
}

.Hide {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<ul class="list">
  <li class="list-entry">
    <p> test 1</p>
    <div class="links">
      <a class="download-link" href="">download</a>
      <a class="list-link">open</a>
      <a class="Hide">hide</a>
    </div>
    <div class="test-div"></div>
  </li>
  <li class="list-entry">
    <p> test 2</p>
    <div class="links">
      <a class="download-link" href="">download</a>
      <a class="list-link">open</a>
      <a class="Hide">hide</a>
    </div>
    <div class="test-div"></div>
  </li>
  <li class="list-entry">
    <p> test 3</p>
    <div class="links">
      <a class="download-link" href="">download</a>
      <a class="list-link">open</a>
      <a class="Hide">hide</a>
    </div>
    <div class="test-div"></div>
  </li>
</ul>

I've also made sure to update the demo to use jQuery v3.6.0 because version 2.1.4 is quite outdated.

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

Percy snap shot test cannot be executed in Testcafe due to the error message: npm ERR! The script 'test:percy' is

For my initial test with percy snapshot, I used the command below: npm run test:percy Unfortunately, an error message appeared when running the command: xxx.xxx@LPG002572 TC-Visual % npm run test:percy npm ERR! missing script: test:percy npm ERR! A com ...

The function jQuery[number] did not get executed

Hello, I have been researching this issue and have come across multiple solutions, but unfortunately none of them seem to work for me. I keep encountering the error message "jQuery21006460414978209883_1395689439888 was not called" when making an AJAX call ...

Explore the capabilities of Vue.js by creating multiple JavaScript classes within your application

<div class="container" :class="{ qwerty: !open }" :class="lower? 'left' : 'right'"> Hey there, I've noticed that Vue seems to only allow me to add one class with conditions, as shown in the exam ...

Error: Trying to access 'whenReady' property of undefined variable is not allowed

As a beginner in electron app development, I am facing an issue when running npm start from the terminal. The error message I receive is: TypeError: Cannot read properties of undefined (reading 'whenReady')... This specific problem seems to be ...

Different Ways to Access an Array in an EJS Template

After receiving a list of IDs from an API, I need to include them in a URL within an EJS template to retrieve the correct items. For example, the URL format is: Here are some example IDs: 526 876 929 The desired output inside the EJS template: <li&g ...

Tips for increasing a numerical value with jQuery within a footnote extension for redactor.js

Currently, I am in the process of developing a plugin for redactor.js that will enable users to include footnotes. The end goal is to have these footnotes stored in a separate table in the database; however, as of now, it's just a mockup for a larger ...

Encountering issues with activeClassName when implementing NavLink in TypeScript

Encountering an issue where I'm receiving the error message "Property 'activeClassName' does not exist on type IntrinsicAttributes" while attempting to utilize activeClassname on NavLink in a TypeScript project. See the code snippet below: i ...

Toggle the visibility of the navigation bar in Angular based on the user

I have implemented rxjs BehaviorSubject in my login page to transmit data to auth.service.ts, enabling my app.component to access the data stored in auth.service.ts. However, I now require the app.component to detect any changes made to the data in auth.se ...

The mobile navigation bar may not display correctly on certain iPhones and iPads

Currently using a custom theme on Prestashop 1.6 where minor changes have been made to the CSS file, focusing mostly on colors and fonts. Interestingly, the mobile menu functions flawlessly on Android devices that were tested. However, some Apple devices s ...

I'm having trouble getting my button to float correctly on the right side

Here I am facing a unique situation where I am attempting to align my button input[type="submit"] to the right side. I have allocated space for it and therefore trying to float the button to the right so that it can be positioned next to my input text. U ...

The Angular Material error message is indicating that the function registerInput is not defined for this._chipList, causing

Issue Description Currently, I am encountering an error when attempting to retrieve input from an <input> tag and showcase it as chips in the graphical user interface (GUI). The console displays the following error message: "TypeError: this._chipLis ...

List created using PHP

After successfully generating a list using PHP with elements selected from a database, I encountered an issue. It seems that when trying to retrieve the index of li elements using jQuery, the indices returned are only odd numbers. For example, clicking on ...

Seeking out and upgrading essential information: how to do it effectively?

I am working with a document in a mongo collection that looks like this: { "_id" :"sdsfsfd323323323ssd", "data" : { "('State', 'Get-Alert', 'BLIST_1', 'MessageData')" : [ "$B_Add-Server", ...

What could be the reason that the MVC controller action method marked as HttpPost is not being triggered by an external JavaScript file?

Below is the View cshtml code that is relevant: <tbody> @foreach (var job in Model.JobsList) { <tr> <th onclick="OnJobSelected('@job.JobID')">@job.JobTitle</th> <th>@job.Statu ...

Attempting to establish a connection with a MySQL database through the utilization of Node.js in combination with the mysql javascript client

Recently, I've been facing a challenge connecting to a MySQL database from my electron app: <script> var mysql = require('mysql'); var connection = mysql.createConnection({ host : '*********', ...

Checking for the presence of HTML controls in the code behind: How to verify their existence

I am working with an asp.net form that contains a textbox and two dropdown lists in a row. Users have the option to add or delete rows using "plus" and "minus" buttons. Upon submitting the form, I gather values from these controls using Request.Form["Con ...

Ensure that the Bootstrap CSS is correctly sizing the background image to fit the screen

body { -webkit-font-smoothing: none; background: url('../img/logo.png') top left; } Bootstrap-CSS : I am trying to design an authentication page and need to use the image logo.png as the background. However, I am facing issues with adapt ...

One CSS file linked, but only one is applied; the other is left unused

After including two CSS files, I am experiencing an issue where only one of them is being utilized. The other file does not seem to be included and the reason behind this remains unknown. My website has a standard header file that is present on all pages. ...

Preserving older items while removing a list item in React

I am facing an issue where I want to remove a specific item from a list. Whenever I click on delete, the correct item gets removed from the list content, but visually on the UI, it always shows the wrong list item being deleted. It seems like there may be ...

Achieving Right Alignment of SVG Next to an <h4> in Bootstrap 5

I'm encountering an issue where I am attempting to align an SVG icon to the right of an H4 element and center it vertically using Bootstrap 5, but it's not working as intended. <div class="container-fluid"> <div class="r ...