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

Is it possible to reveal a concealed element or modify the functionality of a hyperlink?

I have a link in the navigation that includes an animated icon of a + turning into an x. When the icon is in the x state, I want users to be able to close it by clicking on the icon or text. However, I am unsure of the best way to approach this. One op ...

Creating a promise in an AngularJS factory function to perform an operation

When working within an Angular factory, I am tasked with creating a function that must return a promise. Once the promise is returned, additional functionality will be added. SPApp.factory('processing', ['$http', '$rootScope&a ...

Unexpected outcomes from the Jquery contains method

Take a look at this example: http://jsfiddle.net/SsPqS/ In my HTML, there's a div with the class "record" to which I've added a click function. Within the click function, I have the following code snippet (simplified): $(".record").click(funct ...

Manipulate DIV elements with jQuery by selecting them based on their class names and then

Is there a way to use jQuery to eliminate all DIVs on a webpage while preserving their content that have the following specific pattern? <div class="ExternalClass85AC900AB26A481DBDC8ADAE7A02F039">....</div> Please note that these DIVs adhere ...

Problem with CSS creating the Typewriter effect when the third line of text is added

I've been working on a website for my new company and I want to incorporate a typewriter effect on the main page. I came across a tutorial on Medium.com but I'm having trouble adding an additional span to the provided code. Take a look at the lin ...

A valid ReactComponent must be returned in order to properly render in React. Avoid returning undefined, an array, or any other invalid object

While working on my react application, I came across an error that I have been trying to troubleshoot without any success. It seems like I must be overlooking something important that could be quite obvious. *Error: VideoDetail.render(): A valid ReactComp ...

Differentiating Between Observables and Callbacks

Although I have experience in Javascript, my knowledge of Angular 2 and Observables is limited. While researching Observables, I noticed similarities to callbacks but couldn't find any direct comparisons between the two. Google provided insights into ...

What is the best way to design a grid with various squares in React Native?

Here's the design I aim to achieve: I am looking to implement the above layout in react native and ensure it is responsive on all screen sizes. I attempted using flexbox but couldn't figure out how to make the boxes square shaped. The code provi ...

Employ the AJAX call within a fresh popup window

Currently, I have implemented an auto-complete textbox where users can input an actor's name and it works smoothly. There are two buttons on the page - "browse movies" which should display a dynamic dropdown list of movies featuring the actor entered ...

Tips for making a Bootstrap dropdown submenu appear as a 'dropup'

I'm using a Bootstrap dropdown menu with a submenu that should drop upwards while the rest of the menu drops down. How can I achieve this? Here is the code snippet: <div class="dropdown"> <a class="inputBarA dropdown-toggle" data-toggle= ...

What is the correct way to include a variable such as /variable/ in a MongoDB query?

I need help passing in a searchTerm from a variable, what is the best way to do this? const mongoquery = { description: { $in: [ /searchTerm/ ] } }; I attempted it like this initially: const mongoquery = { description: { $in: [ `/${searchTerm}/` ] } }; H ...

What steps can I take to address this issue with my express node and ejs?

Hey there, I'm new to node.js and I've been encountering this error message. Can someone please provide some insight? Error: Could not find matching close tag for "<%=". at /Users//Desktop/Web Development/getting_started_express js/node_m ...

What occurs if we trigger an emit event on a socket that is already disconnected?

If the socket is already disconnected, what are the potential consequences of executing the code below? socket.emit("event", event_data); ...

Passing parameters in a callback function using $.getJSON in Javascript

I am currently using a $.getJSON call that is working perfectly fine, as demonstrated below. var jsonUrl = "http://www.somesite.co.uk/jsonusv.php?callback=?"; $.getJSON(jsonUrl,function(zippy){ ...some code } However, I want to pass a ...

Capture data from clipboard as it is being pasted into Handsontable

Issue Description and Troubleshooting: In a nutshell, I am seeking a method to manage data copied from the clipboard to a handsontable. I came across a suggestion on how to fetch this information using jQuery in a stackoverflow post: $("#haras_excel_li ...

Having trouble sending data from AJAX to PHP

My goal is to implement a "load more" feature in my web app that automatically calls a PHP file to load additional products as soon as the page is fully loaded. In order to achieve this, I am using AJAX to call the PHP file: $(document).ready(function() { ...

The combination of a modal box, checkbox, and cookie feature creates

I am trying to accomplish the following tasks: When the homepage loads, I want a modal box to appear Inside the modal box, there should be a form with a mandatory checkbox After checking the checkbox, submit the form and close the modal box to return to ...

CSS code for targeting specific screen sizes in the Bootstrap grid system

I'm not an expert in styling, but I often use Bootstrap for small projects. Currently, my main challenge lies within the grid system. With one monitor at a 1920x1080 resolution and another at 1366x768, I find myself wanting to adjust the grid system b ...

Challenge with the positioning of HTML output layout

Is there a way to center the output/result of the HTML code below both horizontally and vertically on the web page using CSS? I have tried the following code but it only centers the output horizontally. Vertical alignment is not working properly. Can someo ...

The React DOM is rendered prior to performing the ajax request

Hey there! I'm new to using React and I've been working on a project that involves displaying charts using Fusion Charts. The challenge I am facing is getting the chart to render with dynamic data fetched from an API. Currently, the chart loads w ...