Eliminate the empty space during slide toggling

I am currently developing a website and utilizing the code below:

//SlideToggle
$('a').attr('href', 'javascript:void(0)');
$('a').click(function() {
  $(this).next().slideToggle();
});

$('.container div').addClass('cf');
.hidden {
  display: none;
}
.container {
  width: 100%;
  margin: 0 auto;
}
.container div {
  width: 25%;
  display: inline-block;
  vertical-align: top;
  text-align: center;
  background: lightblue;
  margin: 0 0 0.25em;
  padding: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div><a href="#">See more</a>
    <p class="hidden">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quia ipsam, dolorem illum. Amet officiis dignissimos eligendi excepturi nam, aliquid architecto atque nostrum illo. Ratione nesciunt, id nulla dolores? Blanditiis, praesentium.</p>
  </div>
  ... similar content for other divs ...
</div>

The slideToggle function works as intended. However, I would like to modify it so that the action only affects the bottommost div and not the others. Here is an image illustrating my desired outcome:

https://i.sstatic.net/TIQAo.png

(I do not want to adjust the height of the divs, they should remain unchanged)

Hopefully this clarifies my request. Thank you for your assistance!

Answer №1

There's potential here, but room for improvement...

//Expand and Collapse
$('a').attr('href','javascript:void(0)');
$('a').click(function() { 
       var $self = $(this);
       var index = $self.parent().index();     
$(this).next().slideToggle(100, function() {           
            var margin = $self.parent().toggleClass("active").find("p").outerHeight();   
            if($self.parent().hasClass("active")) {
                 $(".container div").eq(index + 3).css("margin-top", margin);   
            }
             else {
                $(".container div").eq(index + 3).css("margin-top", 0);            
            }                     
        });         
});
$('.container div').addClass('cf');
* {
  box-sizing:border-box;
  }

.hidden {
  display: none;
}

.container {
  width: 100%;
  margin: 0 auto;
}

.container div {
  width: 33.3333333333%;
  display: inline-block;
  vertical-align: top;
  text-align: center;
  background: lightblue;
  margin:0;
  padding: 25px;
  position:relative;
  -webkit-transition: ease-in-out, margin .1s ease-in-out;
  transition: ease-in-out, margin .1s ease-in-out;
  float:left;
}

.container div p {
  position:absolute;
  width:100%;
 left:0;
  padding:25px;
  margin:0;
  top:100%;
  background: lightblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div><a href="#">See more</a>
    <p class="hidden">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quia ipsam, dolorem illum. Amet officiis dignissimos eligendi excepturi nam, aliquid architecto atque nostrum illo. Ratione nesciunt, id nulla dolores? Blanditiis, praesentium.</p>
  </div>
  <div><a href="#">See more</a>
    <p class="hidden">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Error sint nihil labore molestias expedita corrupti ipsa iusto iure sit nisi ab nobis maxime unde voluptates magni, distinctio quae. Deserunt, incidunt.</p>
  </div>
  <div><a href="#">See more</a>
    <p class="hidden">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deserunt accusamus facilis tempore repellat eligendi accusantium laudantium quis, magni a soluta deleniti voluptatibus quam, est aliquid. Atque a, esse. Itaque, consequuntur.</p>
  </div>
  <div><a href="#">See more</a>
    <p class="hidden">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam, quo, possimus. Quam odit laudantium, ex alias, repellat laborum quae nobis expedita aperiam iusto iure at facilis obcaecati doloribus quis earum.</p>
  </div>
  <div><a href="#">See more</a>
    <p class="hidden">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quam ratione doloribus laborum deleniti quae cumque quasi, repellat, ex nemo nulla corporis voluptatum vel doloremque nesciunt cupiditate, veritatis excepturi vero harum.</p>
  </div>
  <div><a href="#">See more</a>
    <p class="hidden">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam cupiditate quisquam, dicta eligendi ut eos culpa nisi quod nesciunt vero soluta voluptates illo esse voluptatibus, ab, sint impedit repudiandae dolorum!</p>
  </div>
</div>

Answer №2

Give this a shot:

Conceal all the p tags prior to executing the Slide toggle function.

$('a').click(function() {
        $('p').hide(); 
        $(this).next().slideToggle(); 
});

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

Expand Tooltip on the Fly

Is there a way to make a tooltip expand horizontally instead of overflowing below the page? I have a tooltip that can be quite lengthy, and due to its max-width being set at 200px, it extends beyond the bottom edge of the page. I am currently able to set ...

What could be causing my v-select title (a string) to split into new lines at the spaces?

When the user clicks to open the dropdown, the v-select v-model value is displayed broken into new lines at spaces. I have attempted to use styling (white-space) and also considered converting the string to an array and looping through it, but that feels ...

What is causing the "Uncaught TypeError: Cannot set properties of undefined (setting 'src')?" error message to appear in my code?

When attempting to change the src of an image using JavaScript within PHP, I encountered an error: Uncaught TypeError: Cannot set properties of undefined (setting 'src'). This issue left me puzzled. As you can see, I retrieved some values from a ...

Utilizing React to Extract the Value Following a Colon in the Document Object Model

Wanting to create a test for verifying the presence of text following a specific value in my HTML file: <span>Dog facts: something</span> The goal is to confirm that there is text after the phrase "Dog facts:" and it is not null. It's im ...

The second JSP page fails to load following an AJAX POST request

The following code snippet is found in page1.jsp. $.ajax({ type: "post", url: "page2.jsp", data: newdata, success:function(msg){ return msg; } ...

How can you transfer a function to another function within the render return statement?

I am encountering an issue when attempting to pass a function to another function. The initial function successfully downloads JSON data and returns it. However, the subsequent function, which is meant to convert the JSON data to HTML code, is not functio ...

CSS - Creating a stylish break line for link boxes

Struggling with creating a box that includes linked text and a line break. However, the issue arises when the line breaks, causing the box to also break. After trying multiple options, I still can't seem to find a solution. Check out my attempt her ...

Ways to prevent onMouseDown from triggering when the element is exclusively clicked?

I'm currently working on developing a game where units (svg elements) are controlled using React. In this game, the units should be draggable, and clicking on a unit should open a form. However, when I click on the unit, only the mousedown event is t ...

Circular reference in Angular/TypeScript

I encountered a circular dependency issue in my Angular project and tried various solutions, including exporting all dependent classes from a "single file" as suggested here. Unfortunately, this approach did not work for me. I then explored other solutions ...

Ways to create a border button with a matching width to the text above using CSS

Is it possible to style a border button in CSS so that the width matches the text above? I am trying to achieve a clean look for the navigation selected text, where the border-bottom aligns with the text above. Here is an example of what I have attempted ...

Leveraging an array retrieved through JQuery AJAX for auto-complete data in materializecss

I am delving into materializecss for the first time, aiming to enhance its auto complete feature by incorporating an array of options obtained from a database. Unfortunately, my attempts have not been successful. After scouring through Stack Overflow and o ...

Tips for hiding a div only on mobile devices while always displaying it on large screens using AngularJS or CSS

How can I use Angularjs or css to hide a div on mobile devices only, ensuring that it is always displayed on large screens? ...

Ways to display jQuery values as HTML text

Trying to concatenate the HTML text with the values of item.certificate_name has been a challenge for me. I've experimented with various methods, but none of them seem to work. The specific line I'm referring to is where I wrote . I have alread ...

Using sql.js to import CSV files into SQLite databases

Is it possible to import a CSV file into a SQLite database using JavaScript instead of the command line? I am currently utilizing the sql.js library to work with SQLite in Javascript. I appreciate any help or suggestions on how to accomplish this task. Th ...

What is the best way to obtain a list of all product names?

I need to extract only the names of the objects (cat, dog, bird) /// Names of objects I want to retrieve /// var storage = [ {cat: {name: "Garfield", count: 3443, price: 1000}}, {bird: {name: "Eagle", count: 4042, price: 3000}}, {dog: {nam ...

An effective method for converting a string into a two-dimensional array using JavaScript

One challenge I am facing is checking from a string if a specific fruit has the correct amount on a given date. I've managed to achieve this by converting the string into a 2D array and iterating over the columns. While this method works, I can't ...

Having trouble updating the input value in AngularJS?

As I venture into customizing an AngularJS tutorial on a Saturn Quiz, I am transforming it from multiple choice to a fill-in-the-blank quiz. The challenge I face is that the first answer registers as correct or incorrect, but subsequent questions always s ...

Ordering Arrays based on a particular attribute

My array includes user points as follows: let groupRank = []; userA = ["Sara", "24"]; userB = ["John", "12"]; userC = ["Eddi", "20"]; userD = ["Marry", "13"]; I am looking to rank them according to their points and achieve the following result: Console ...

Contrasting .queue() with jquery.queue()

Can someone clarify the distinction between .queue() with .dequeue() and $.queue() OR jquery.queue()? If they serve the same purpose, why did jQuery provide them in two separate documentations? Could someone provide examples to illustrate their difference ...

Utilizing Bootstrap accordion to trigger distinct actions on elements within open and close cards

Currently, I am designing an accordion using Bootstrap 4. Each card header in the accordion has a background image that needs to be hidden when its corresponding body is open and shown when it is closed. The objective is to display all images on closed ca ...