Toggle visibility of various items in a to-do list, displaying only one item at a time with the use of JavaScript

I am currently working on a web project using the Laravel framework. I am struggling with implementing a feature where only the title of each to-do item is displayed, and when clicked, it should reveal the corresponding content. However, I have encountered an issue where this functionality only works for the last item in the list.

<div class="container-fluid">
                    <h1>Painted List <a href="/create" class="text-success"><i class="fa fa-plus"></i></a></h1>
                    <ul>
                    @if(count($paints) > 0)
                    @foreach($paints as $paint)
                            <li onclick="myFunction()"><span><i class="fa fa-trash"></i></span> {{ $paint->title }}</li>
                            <div class="card-body" id="contentBody">
                                <p class="content"> {{$paint->content}} </p>
                            </div>
                            <script>
                            function myFunction() {
                            var x = document.getElementById("contentBody");
                            if (x.style.display === "none") {
                                x.style.display = "block";
                            } else {
                                x.style.display = "none";
                            }
                            }
                            </script>
                    @endforeach
                    @else
                    <li><span><i class="fa fa-trash"></i></span> No Paint yet!</li>
                    @endif
                    </ul>
                </div>

I'm seeking assistance in refining my code to ensure that only one piece of content is shown at a time when clicked, using CSS, JavaScript, and HTML.

Someone helped me in getting the content to show and hide upon clicking, but the issue persists where all contents are displayed when multiple titles are clicked Referencing this image, you can see the problem in action

Answer №1

Make sure to include the onclick function within a div element inside an <li> tag to allow for returning to the parent <li>. Also, place the card-body element inside the <li> and use a <script> outside of the foreach loop to prevent redundancy.
Give this a try:

<div class="container-fluid">
<h1>Painted List <a href="/create" class="text-success"><i class="fa fa-plus"></i></a></h1>
<ul>
    @if(count($paints) > 0)
    @foreach($paints as $paint)
    <li>
        <div onclick="myFunction(this)"><span><i class="fa fa-trash"></i></span> {{ $paint->title }}</div>
        <div class="card-body" id="contentBody">
            <p class="content"> {{$paint->content}} </p>
        </div>
    </li>
    @endforeach
        <script>
            function myFunction(el) {
                var p = el.parentNode; // return from div you clicked it to <li>
                var x = p.querySelector('.card-body');  // find card-body
                //var x = document.getElementById("contentBody");
                if (x.style.display === "none") {
                    x.style.display = "block";
                } else {
                    x.style.display = "none";
                }
            }
        </script>
    @else
    <li><span><i class="fa fa-trash"></i></span> No Paint yet!</li>
    @endif
</ul>

An efficient approach is to utilize JQuery for simplicity, as Laravel can be sensitive to in-scripts due to security concerns.

$('.non').on('click', function(e){
   if (e.target.nextElementSibling.style.display === "none") {
     $('.contentBody').hide()
    e.target.nextElementSibling.style.display = "block";
} else {
  e.target.nextElementSibling.style.display = "none";
}
 })

A friend of mine noticed my dejected expression, then performed some magic that only Js clipless comprehends.

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

Guide on sending several HTTP requests from a Node.js server with a shared callback function

Is there a way to efficiently make multiple HTTP calls in a Node.js server with a shared callback function? Are there any modules or libraries that can help with this? ...

Utilize vue-resource for updating information in the database

Within my Vue component, I have the following data setup: data() { return { revenueChart: '', limit: 12, labels: '', datasets: '' } }, In addition, there is a method that utilizes vue- ...

Troubleshooting Problems with Bootstrap 3 Radio Group Buttons and Making Ajax Requests

How can I use the Radio Toggle Button groups in Bootstrap 3 to get the checked/selected radio and send it through ajax? I have tried using $('#loaditems').click but it is not working as expected. <div class="btn-group btn-group-sm" data-toggl ...

Invoke a functional component when a button is clicked in a React application

I have a functional component that includes a button. My goal is to trigger another functional component when this button is clicked. Upon clicking the Submit button, the Preview button appears. When the user clicks on the preview button, it should call t ...

managing, modifying and removing information within the app.controller in AngularJS

I am currently facing a challenge with my Javascript code for a simple web application that involves AngularJS. Here is the snippet of code I am working on: app.filter('startFrom', function () { return function (input, start) { if (i ...

Error message in my Angular project: Invalid Target Error

Out of nowhere, I encountered an invalid target error while running my Angular project with the command: npm start An unhandled exception occurred: Invalid target: {"project":"agmbs","target":"build","configur ...

Vue Native Script refuses to install

Attempting to utilize vue-native, I encountered an issue while trying to install vue-native-scripts via npm. PS E:\Coding\VueNative\YAAdmin> npm i vue-native-scripts npm WARN optional SKIPPING OPTIONAL DEPENDENCY: <a href="/cdn-cgi/l ...

Discover how to retrieve full response data by entering text into a text field using Reactjs

I am encountering an issue while retrieving values from rendered data in a component that has already been displayed on the page. I want to input data into a text field and have it sent to the database, but using the runtime data from that specific field. ...

What is the best way to utilize XMLHttpRequest for sending POST requests to multiple pages simultaneously?

I have a unique challenge where I need to send data to multiple PHP pages on different servers simultaneously. My logic for sending the post is ready, but now it needs to be executed across various server destinations. var bInfo = JSON.stringify(busines ...

Using jQuery's each method to implement dynamic fallback with JSON data

Is it possible to set a fallback function dynamically from an AJAX JSONP call? I've been trying, but it doesn't seem to work. I'm not sure if I'm doing it right. Here's what I have: var GetFacebookData = function (data) { ...

Instructions for incorporating highcharts sub modules into a React application

I have been utilizing the react-jsx-highcharts library to seamlessly integrate Highcharts into my React application. Everything is functioning perfectly. However, I am now interested in incorporating the boost module. I attempted to add it by simply using ...

When using Nuxt JS and Jest, a warning message may appear stating "[Vue warn]: Invalid Component definition" when importing an SVG file

I am facing a unique issue only in my Jest unit test where an error occurs when I import an SVG into the component being tested: console.error node_modules/vue/dist/vue.common.dev.js:630 [Vue warn]: Invalid Component definition: found in -- ...

Guide on effectively sorting the second level ng-repeat data in a table

I have a collection of data objects that I want to present in a tabular format with filtering capabilities. The current filter, based on the 'name' model, successfully filters the nested object 'family'. However, it does not function as ...

Only IE7 seems to be experiencing a z-index problem with CSS that is not present on any

I’ve encountered a perplexing problem with CSS z-index in IE7 that I just can’t seem to solve. #screen { display: none; background-image: url('/images/bg.png'); background-repeat: repeat; position: fixed; top: 0px; le ...

Tips on displaying the menu only when scrolling through the webpage

Currently, my website has a right menu that causes overlap with the content on mobile and small devices. To address this issue, I am working on hiding the right menu when the page is stable. The plan is for the menu to appear as soon as the user starts sc ...

Is it possible to implement slickgrid with paging, checkbox selection, sorting, and filtering for handling extensive datasets successfully?

I have configured a slickgrid to handle up to 500,000 records efficiently or less (500k being the maximum limit). The slickgrid includes features such as paging, sorting, inline column filtering, and row selection using checkboxes, all of which are operat ...

Inject an html <img> tag using an AJAX PHP call

Greetings everyone, I am currently in the process of developing a captcha maker using PHP with an Object-Oriented Programming (OOP) approach. The implementation involves a Captcha class responsible for generating the captcha image. You can find the complet ...

Searching for a streamlined approach to retrieve a segment of a string

I'm currently working with JavaScript and TypeScript. Within my code, I encountered a scenario where I have a string that might contain certain tags indicating importance or urgency. Here are a couple of examples: A: "Remind me to go to the store to ...

Utilizing the $.ajax method to navigate to a webpage displaying only the results that correspond to the value in the json data

I'm in the process of creating a single page application that utilizes $.ajax. Here is the JSON data: { "restaurants": [ { "id": 1, "name": "Denny's", "location": "Los Angeles", "cuisine": "American", "image_ ...

Assistance required with extracting information from JSON format on a website

Seeking assistance in displaying the last 10 songs played on a web page using JSON data. The current code is not fetching and showing the requested information from the json file. https://jsfiddle.net/Heropiggy95/6qkv7z3b/ Any help in identifying errors ...