Displaying a single item per click using jQuery

Hey there, I have a small issue with some HTML divs and show/hide functionality.

I'm trying to make it so that only one div is shown per click, but my current jQuery code is showing all the divs at once.

Any suggestions on how to fix this?

Check out the code here

jQuery(document).ready(function() {

    var toggleContent = jQuery('.insideContent');
    toggleContent.addClass('hidden');
    var thisElemnt = $(this);
    jQuery('.button').on('click', function() {
        thisElemnt.find('.insideContent').removeClass('hidden').addClass('show');
    });


});

jQuery(document).ready(function() {

  var toggleContent = jQuery('.insideContent');
  toggleContent.addClass('hidden');
  var thisElemnt = $(this);
  jQuery('.button').on('click', function() {
    thisElemnt.find('.insideContent').removeClass('hidden').addClass('show');
  });


});
.hidden {
  display: none !important;
}
.show {
  display: block !important;
}
.list {
  direction: inherit;
  display: flex;
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="list">
  <div class="col-lg-2 workImage">
    <div class="itemTitle">
      <h2 class="page-header  text-center">Item</h2>
      <button class="button">Open Project</button>
    </div>
    <div class="insideContent">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>
  </div>
  <div class="col-lg-2 workImage">
    <div class="itemTitle">
      <h2 class="page-header  text-center">Item</h2>
      <button class="button">Open Project</button>
    </div>
    <div class="insideContent">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>
  </div>
  <div class="col-lg-2 workImage">
    <div class="itemTitle">
      <h2 class="page-header  text-center">Item</h2>
      <button class="button">Open Project</button>
    </div>
    <div class="insideContent">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>
  </div>
</div>

Answer №1

jQuery(document).ready(function() {

    var toggleContent = jQuery('.insideContent');
    toggleContent.addClass('hidden');
    var thisElemnt = $(this);
    jQuery('.button').on('click', function() {
        $(this).closest('.itemTitle').next('.insideContent').toggleClass('hidden show');//apply the click element only
    });


});

Utilize .closest() to locate the nearest parent container with a class of .itemtitle, then utilize .next() to target the following div, and finally use .toggleClass() to display or hide the targeted div.

VIEW DEMO

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

I'm looking for a way to dynamically update Laravel pagination records based on the selected option value for the number of items per page using Laravel and

I am working on creating a custom filter system using a select option menu and pagination with AJAX. The select option allows users to choose between displaying 10, 15, 20, or 25 products per page while updating the Laravel default pagination dynamically ...

The outline none property on the Material UI IconButton is malfunctioning

https://i.sstatic.net/S5zWD.png Attempting to style with CSS as shown in the following example: <CustomColorIconButton> <DeleteForeverIcon /> </CustomColorIconButton> const CustomColorIconButton = withStyles({ root: { c ...

loop not functioning properly with file type input

Having trouble uploading an image and copying it into a folder named images within a loop. Can you assist with solving this issue? Here's my code: $sql="SELECT * FROM product"; $q=$conn->query($sql); while($r=$q->fetch(PDO::FETCH_ASSOC)) { $cod ...

What is the best way to position a button on the right side of the page, ensuring that all text

I need help aligning my button (JSX component) to the right side while ensuring that all text remains on a single line. I am working with next.js and tailwindcss, and the button includes plain text as well as a react-icon. These components are all wrapped ...

What is the best way to create a sliding menu that appears from the right side on a mobile device using HTML, CSS, and JQuery

Is there a way to have the menu slide in smoothly from the right side after clicking on the menu bar icon, including sliding the menu bar icon itself? The current code displays the menu directly upon clicking on the menu bar, but I would like it to slide i ...

Stop the duplication of downloading JavaScript files

When it comes to my website, I have incorporated sliders that stream videos from Vimeo. Upon running a check on GTMetrix, I noticed an overwhelming number of http requests. Looking at the waterfall, I discovered numerous duplicate downloads of javascript, ...

Display each div one at a time

I am working on a script that should reveal my divs step by step. However, the current code only shows all the divs at once when clicked. How can I modify it to detect each individual div and unveil them one by one? For example, on the 1st click => expa ...

What is the recommended way to include an image in a v-for loop in Vue.js?

I have attempted various online solutions, but I am still unable to display images on the screen. Could it be a simple mistake? The file names and folders are accurate. When providing the path, I aim to retrieve the image associated with the sub-club name ...

initiating an ajax request when the button is clicked

Would love some help with my code! I've got a basic html button that triggers an ajax call. This is the button's code snippet: <INPUT type="button" class="form6form" id="newsubmit" name="newsubmit" value="Submit"> And here is the full ...

Ensuring the text is positioned centrally and at the bottom of a table cell

Is there a way to center and align text at the bottom of a cell in table? This is my desired layout: ...

Invalid Jquery syntax: Anticipated an assignment or function call but encountered an expression instead

Here's a simple code snippet: _create: function () { var self = this; $("#Grid").on("click", ".Row", function () { $(self).hasClass('Expanded') && $('html, body').animate({ ...

Using Ajax to submit a form on a Spring MVC webpage

I need help with submitting a form using AJAX post without refreshing the page. My technology stack includes Spring and jQuery. Can someone guide me on how to submit the form via AJAX and utilize the class in the controller for processing? The model Clas ...

Is there a way to deactivate the save button in CKEditor?

I am currently not interested in using any ajax functionality within ckeditor. Is there a way for me to remove that button from the toolbar? Whenever I click on the save button without disabling it, I encounter strange errors. I found guidance on this topi ...

Could a css style be applied to a parent element based on the status of its child element?

In my specific context, this is the HTML code I have: <div class='table'> <div> <div *ngFor='let product of this.market[selectedTab].products | orderBy:"id"' class='itemlist' [ngClass]="{' ...

How to retrieve PHP variables in jQuery Ajax syntax

I have a custom PHP function to send messages: <?php function sendMessage($userId, $projectId, $message) { //some code } $userId = '1'; $projectId = '2'; $message = 'hello'; ?> <form id="myForm" method="post" ac ...

The live() function is causing issues with my ajax request

Within my webpage, I have a link with an onclick() event that should display a div containing a date input text named "datepicker0", followed by another div with the id of "bContent". I've included the script below to implement a date filter on the d ...

When a specific option is selected in a `select` element with the `multiple` attribute, activate the change event

Is it possible to trigger a change event on individual options within a standard select element using jQuery or another method? I want the change event to be triggered on the option elements themselves rather than on the select element, as multiple options ...

Setting the default styling for unordered lists in Material-UI React is a breeze with these simple steps

Currently, I am attempting to recreate a basic blog using markdown with Next.js and Material-UI. However, it appears that something is stripping away the default styles from unordered lists. The list items (HTML elements) have been set with list-style: no ...

How to eliminate vertical spacing between rows in Bootstrap?

I am looking to eliminate the unsightly vertical spacing between the bootstrap rows displayed below: https://i.sstatic.net/dgR2z.png The code appears as follows: <div class="outerbox container-fluid vw-100"> <div class="row vw-100 justify-co ...

Does setInterval run only once?

JSFiddle is here... http://jsfiddle.net/Vd8PJ/10/ Currently, I am attempting to create a JQuery carousel that can showcase images of varying widths. The goal is to achieve a seamless and infinite slide to the right on an unordered list containing these i ...