What is the best way to toggle the visibility of elements within a single div container?

Can someone assist me with a peculiar issue I am facing?

I am attempting to toggle the visibility of certain elements when a user clicks a button.

Here is my HTML structure:


   <div class='slide-content'>
        <h1>Title</h1>
        <div class='title-bar'>
            sub title here
            <div class='edit-container'>
                <a class='edit' href='#'>Edit</a>
            </div>
        </div>
        <div id='content' class='details'>
            <div class='contents'>
                 <p>contents here</p>
            </div>
            <div class='break'></div>
        </div>
        <div id='edit-content' class='content-details'>
             <div class='contents'>
                <div class='editable-content'>
                    contents here…...                          
                </div>
            </div>             
            <div class='break'></div>
        </div>
    </div>

    <div class='slide-content'>
     …...

Followed by 10 more "slide-content" divs...

My jQuery code snippet:


   $('.edit').on('click', function(e){
       e.stopPropagation();
       if($(this).text()=='Edit'){
           $(this).text('Done');
           $(this).closest('.slide-content').find($('.content-details')).show();
           $(this).closest('.slide-content').find($('.details')).hide();
       }else{
           $(this).text('Edit');
           $(this).closest('.slide-content').find($('.content-details')).hide();
           $(this).closest('.slide-content').find($('.details').show());
       }
   })
});

CSS style for .content-details:

.content-details{
  display:none;
}

The problem arises when I click the 'edit' button for the first time - it correctly displays my ".content-details" and hides the ".detail" div. However, upon clicking the 'edit' button again, it shows every ".details" div on the page (even those under different ".slide-content" divs). My intention is to only show one ".detail" div under the current ".slide-content."

I seem to be missing something in my logic. Any assistance would be much appreciated. Thank you!

Answer №1

Your parentheses are not properly closed here:

$(this).closest('.slide-content').find($('.details').show());

To highlight the issue more clearly:

$(this).closest('.slide-content').find(
    $('.details').show()
);

it seems like you are explicitly invoking $('.details').show().

The correct way to write this is:

$(this).closest('.slide-content').find($('.details')).show();

However, you can actually simplify it further by removing the unnecessary jquery object for find(), like so (you can apply this pattern in other places as well):

$(this).closest('.slide-content').find('.details').show();

Additionally, I recommend streamlining your code and utilizing caching a bit:

$('.edit').on('click', function (e) {
    e.stopPropagation();
    var $this = $(this);
    $this.text($this.text() == 'Edit' ? 'Done' : 'Edit');
    $this.closest('.slide-content').find('.content-details, .details').toggle();
});

Answer №2

All you really need is this link: http://jsbin.com/IsUQaJA/1/edit

$('.edit').on('click', function(e){
       e.preventDefault();   
       var txt = $(this).text();
       $(this).text(txt=='Edit'?'Done':'Edit').closest('.slide-content')
              .find('.details, .content-details').toggle();
}); 

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

Uncovering the Mystery of AJAX and JSON in jQuery and NodeJS

Currently, I'm facing a challenge with an ajax function that sends a json to a nodejs route. I need to extract the selected values from 4 button-groups named quality, costeffectiveness, deliveryscope, and rating. Each button-group consists of 5 radio- ...

Develop a dynamic modal feature that allows users to input SQL queries and execute them seamlessly without having to

I need to implement a feature in my web application where users can set the price of an item displayed in an HTML table that is populated from a MySQL database. When a user clicks on a button next to a row, a modal should open with a text input field and a ...

How to use jQuery to retrieve and display an image from a JSON object

My current task involves extracting content from a JSON object and showcasing it on a webpage. While I am successful in retrieving the object and cycling through to extract different content, I encounter an issue with displaying images alongside first and ...

Incrementing numbers with jQuery append autoincrement

I am working with a dynamic list of input fields, each one with a unique incremental name. Here's an example structure... <input type="text" name="values[0]" value="some text"> <input type="text" name="values[1]" value="some other text"> ...

The HTML Email Template fails to incorporate certain CSS styles

When attempting to create an HTML Email template that includes a button with a link and has a maximum width with consistent margins on both sides, I encountered some issues. While certain parts of the CSS were applied correctly, others were not displaying ...

Sending a variety of inputs through an Ajax Request using Razor

I'm currently in the process of constructing a web API, and my goal is to utilize ajax to query a web service that requires two arguments. I need to transmit a List of Strings (SSNs) as well as a single string to specify the environment it should quer ...

Despite passing JSLint, an unexpected end of input still occurred

It seems a bit absurd; despite my efforts, I'm unable to locate the syntax error. The Chrome debugger keeps indicating an "unexpected end of input" in line two. Any suggestions? $("head meta").each(function () { var content = JSON.parse(this.cont ...

Sharing the latest updates on fyneworks' star rating information

Currently, I am incorporating a star rating system into a sports website where users can rate events post-occurrence. During my research, I came across this informative post: JQuery Star Rating This resource seems to align perfectly with what I need, but ...

An issue arises in Django where a particular field fails to display the accurate value when presented in a template

models.py The Order model in models.py defines various fields such as user, customer, card_id, mobile, email, total_price, payment_method, status, take_method, points_earned, date, and address. It also includes preset choices for payment options, order sta ...

What is the best way to navigate through images only when hovering?

I have a website that showcases a collection of images in a creative mosaic layout. Upon page load, I assign an array of image links to each image div using data attributes. This means that every image in the mosaic has an associated array of image links. ...

Generate a unique Guid in ASP.NET MVC with the click of a button

When clicking a button, I want to generate a new GUID without reloading the entire view. However, I'm struggling to figure out how to achieve this. This is the function I currently have: Guid.NewGuid() I attempted to do this in JavaScript by adding ...

Create a dynamic feature that allows users to easily add text fields within a form in

I'm looking to create a form that adds another input text field automatically when the user fills out one. Here is an example of the HTML structure: <form method="post" action="http://localhost/save" class="save"> <fieldset> <div&g ...

The image sits on the edge of the container, not fully contained

.sub2 { background-color: #FFFFBF; margin-top: 30px; height: 410px; width: 100%; } h1.sub2 { font: bold 100px american captain; text-decoration: underline; float: right; } p.sub2- { font: italic 25px american captain; margin-top: -300px; ...

Enhancing choices for a select tag that is generated dynamically

I am encountering challenges while adding options to the dynamically generated select tags using jQuery. The options are fetched from a database, and I want to display all these options for each dynamically created select tag. Could you please point out w ...

Managing various dropdown select options in pure JavaScript

Consider the select element provided below: <select multiple="multiple"> <option value="car">car</option> <option value="scooter">scooter</option> <option value="bus">bus</option> </select> I ...

Is there a way to determine the length of the visible section of an overflowing element?

Currently, there is a table with numerous rows causing it to overflow the vertical axis of the document viewport: https://i.sstatic.net/YoqKk.png As you can observe, only a portion of the table is visible when the document loads. How can we determine the ...

Creating additional fields in the MySQL database specifically for the newsletter

While I have a basic understanding of PHP and MySQL, creating a newsletter from scratch has proven to be quite challenging for me. Luckily, I stumbled upon a newsletter tutorial on Git Hub that caught my attention. I am interested in implementing this new ...

Why is the Material UI React select not selecting all children except for the last one?

I have a challenge with selecting specific children: const useStyles = makeStyles(theme => ({ icons: { "&>*": { backgroundColor: "red", }, }, })) This is how it looks in JSX: <Grid item> < ...

Create a scrollable div using the flex-grow-1 class in Bootstrap 5

I'm having trouble making the div below scrollable. Instead of producing a scrollbar, it keeps expanding the document size beyond the screen space. I know I could set a fixed pixel height for the div, but I want to make sure it scales well across diff ...

A button that is positioned with a low z-index may be unresponsive to

I am working on aligning an image and a button next to each other so that the image slightly overlaps the button. However, I have noticed that in doing so, the button becomes unclickable. .button{z-index:-1!important;} .image{z-index:1!important;} Any s ...