jQuery divs display and conceal

Looking for help with this code structure:

Here's the HTML:

<div class="container">
    <button class="a">Button</button>
    <div class="b" hidden="hidden">Content</div>
</div>
<div class="container">
    <button class="a">Button</button>
    <div class="b" hidden="hidden">Content</div>
</div>

And here's the jQuery code:

$(document).ready(function () {
    $('.a').click(function () {
        if ($('.b').is(":visible")) {
            $('.b').hide();
        } else {
            $('.b').show();
        }
        return false;
    });
});

How can I modify this to only show the div that was clicked on?

JSFiddle.

Answer №1

Feel free to utilize the following code snippet. View the DEMO

Discover more about jquery's next() function.

Retrieve the immediate next sibling of each element within the matched elements. If a selector is specified, it will only fetch the next sibling if it meets that criteria.

 $(document).ready(function () {
   $('.a').click(function (e) {
     e.preventDefault();
    // $('.b').hide();  if you want to hide opened div uncomment this line
     var bOBJ = $(this).next('.b');
    if (bOBJ.is(":visible")) {
        bOBJ.hide();
    } else {
        bOBJ.show();
    }
    //return false;
  });
});

Alternatively, explore another method in the DEMO

Learn about Jquery's toggle() functionality

Show or hide the selected elements.

 $(document).ready(function () {
   $('.a').click(function (e) {
     e.preventDefault();
     // $('.b').hide();  if you want to hide opened div uncomment this line  
    $(this).next('.b').toggle();
     //return false;
   });
 });

Answer №2

When searching for the nearest div.b, you can utilize jQuery.siblings(). Instead of relying on .show() and .hide(), consider using jQuery.toggle()

$(function() {
    $('.a').click(function() {
        $(this).siblings('.b').toggle();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
    <button class="a">Button</button>
    <div class="b" hidden="hidden">Content</div>
</div>
<div class="container">
    <button class="a">Button</button>
    <div class="b" hidden="hidden">Content</div>
</div>

Answer №3

PLEASE VERIFY

 $('.a').click(function () {
        
            $('.b').hide();
        $(this).siblings('.b').show();
       
        return false;
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="container">
    <button class="a">Button</button>
    <div class="b" hidden="hidden">Content</div>
</div>
<div class="container">
    <button class="a">Button</button>
    <div class="b" hidden="hidden">Content</div>
</div>

Answer №4

Kindly refer to the code snippet below

$('.toggle').click(function(){
$(this).next('.content').slideToggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="container">
    <button class="toggle">Toggle</button>
    <div class="content" hidden="hidden">Lorem Ipsum</div>
</div>
<div class="container">
    <button class="toggle">Toggle</button>
    <div class="content" hidden="hidden">Dolor Sit Amet</div>
</div>

Answer №5

    $(document).ready(function () {
    $('.click-me').on('click', function () {
        var parentNode = $(this).parent();
        var targetContent = parentNode.find(".inner-content").first();

        if ($(targetContent).is(":visible")) {
            $(targetContent).hide();
        } else {
            $(targetContent).show();
        }
        return false;
    });
});

Answer №6

If you want to display and conceal an alternative, the .toggle() method can be used effectively. Give this a shot.

 $(document).ready(function () {
  $('.a').click(function () {
   $(this).next('.b').toggle(1000);
 });
});

Answer №7

If you're looking for a quick and simple solution, you can find it here: sfiddle.net/webyourway/aahqh80q/9/

The use of the 'hidden' HTML attribute is quite uncommon. Personally, I've never used it before. It seems that this attribute should be reserved for elements that need to be hidden regardless of presentation. In your situation, using CSS display:none may be a better option.

$(document).ready(function () {
    $('.a').click(function () {
        $('.b').hide();
        $(this).next('.b').show();
    });
});

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

Two keyframes are unable to function simultaneously

I am facing an issue with transitioning two divs, "hat" and "sock". The "hat" transition works as intended, but for some reason, the "sock" transition is not working. I have checked the properties and made sure they are set up in a similar way to "hat", ...

How to hide functions in Angular source code

Here's a common query. Typically, the code we develop in Angular gets compiled into a bundle file that is then sent to the browser, correct? The JavaScript code we write can be easily seen as is in the bundle file when viewing the source. How can we ...

Freemarker substitute & and &ampersand;

I am facing an issue with Freemarker. I need to eliminate all the special characters from this sentence as well as from similar sentences in the future: BLA BLA RANDOM &, RANDOM BLA In particular, I want to remove the & character. The platform ...

The error encountered is an unhandled rejection with a message stating "TypeError: Cannot access property 'username' of null

My tech stack includes NodeJS, PassportJS, MySQL, and Sequelize (ORM for MySQL). The following code snippet is taken from my Passport.JS file. Whenever a user registers on my website, an error is returned if the username or email is already in use. If both ...

What is the best method to display a tooltip for a disabled radio button within a set of radio buttons?

Is there a way to disable a specific radio button based on a condition and display a tooltip only for that disabled button? https://i.stack.imgur.com/niZK1.png import {Tooltip} from '@mui/material'; <Tooltip titl ...

What could be causing my Time Picker MUI to malfunction in my React project?

I am currently working on a React and Rails project where I am attempting to style my React components. However, I have encountered an issue with the MUI component Time and Date picker. Whenever I try to implement the time picker, I get a strange error reg ...

focusing on two different sections with a single hover effect

Is it possible to modify the styles of two different divs using CSS when hovering over one div? #down-icn { position: absolute; bottom: 0; right: 25px; color: #fff; -webkit-transition: color 0.25s ease; border-color 0.5s ease; -moz-transition: colo ...

When using JavaScript to style.display = "block", the Bootstrap-4 column layout may experience a display break

My div is initially displaying properly in one row at the beginning. However, when the user changes the select option to "b" and then back to "a," the display breaks. The two texts "my left side text" and "my right text" are displayed on two lines, one be ...

Disable the form options listed on the table

I have a scenario where I have a table and a form containing a dropdown list: <table> <tr> <td class="text">Apple</td> <td class="name">John</td> </tr> <tr> <td class=" ...

Ways to invoke external jQuery functions within Angular applications

In the midst of working on an Angular CLI Project, I find myself needing to incorporate some jQuery functionalities. To accomplish this task, I have added the necessary JavaScript files in the angular.json configuration: "scripts": [ "node_modules/jq ...

Sequential jQuery AJAX requests triggering in an incorrect sequence

One challenge I am facing involves a select list with bundles of short texts. Upon selecting a specific bundle, the texts are displayed in two tables. Each table row has a "Delete" icon to remove a text from the bundle. I am aiming to refresh both the tabl ...

How can I pass the dynamically generated ID from PHP to AJAX/jQuery using an anchor tag?

I'm seeking help with jQuery and Ajax as I am new to it. My issue is that I have multiple 'edit' buttons in a table, one for each row's data. When I click on an edit button to modify the data, they all open at once instead of just the s ...

Having trouble loading xml/xsl files on IE11? Consider enabling compatibility mode to ensure smooth rendering on your xml/xsl page

On my website, I have a page that displays XML from an XSL document. Strangely, it works perfectly on IE8 but not on IE11 - the page appears blank even though the XML is present when viewing the source. Interestingly, if I enable compatibility mode for the ...

Delete the designated column from the table

I am having difficulty with hiding and showing table columns using checkboxes. I need to eliminate the Mars column (in bold) along with its corresponding data (also in bold). Once the Mars column is removed, I want the Venus column and its data values to ...

Hidden input field when inactive

Whenever I start typing in my input form, the text disappears after a moment. The only way to prevent this is by continuously pressing on a letter key on my keyboard. This issue began after I added a resizeInput attribute that adjusts the size of the inpu ...

When the dropdown menu is displayed, apply a class to the parent <li> element's

Encountering a frustrating problem where I'm trying to assign a class to an li a when its submenu is visible. However, the class is being added to all li a elements, including those in the submenu. <ul id="nav"> <li><a href="#" tar ...

Unable to change the color of the tab indicator

Hello, I am currently using materializecss in conjunction with Angular 6. Just to clarify, I am solely utilizing the materializecss library and not ng2-materialize. My issue arises when attempting to customize the tab indicator background color by modifyi ...

Executing a transaction in Firestore

I am currently developing an application that utilizes Firestore to store user data. One issue we are facing is that writing data to a Firestore document is not in real time, which becomes problematic with higher write frequencies. To address this issue, ...

Issues Arising When Transmitting a Multidimensional Array from Jquery to PHP - Where Am I Going Astray?

I'm struggling to send a multidimensional array [N][N] from JavaScript to PHP. Despite trying several solutions I found here, I can't seem to figure out where I'm going wrong. Below is the JQuery code I'm using to save values from an H ...

Adjusting the height of an element in AngularJS based on its width dynamically

I am working on a table that is generated using ng-repeat, and I want to ensure that each td in the tbody is square. Since all the tds have an equal width, I only need to adjust the first one. However, the size of the table and td will change when the wind ...