What is the best way to make the <li> move down when displaying a hidden div?

I'm currently attempting a task that I'm unsure is possible.

Within my li elements, I have hidden divs containing additional content. When I click on an li, the corresponding div is displayed below with a 100% width. However, instead of pushing down the other divs, it overlays them. I understand that using absolute positioning won't push the content down, but I'm not sure how to achieve a 100% width without it.

What I would like is for the hidden div to display beneath its respective li, taking up the entire width of the window, and for any subsequent lis to appear below this content. Essentially, clicking on an li in the first row should reveal a hidden div below it, while maintaining the structure of the grid layout.

You can view the current code here

I welcome any changes or suggestions for the JS or CSS implementation.

I hope I've provided a clear explanation. Could you assist me with this query?

Thank you!

$('.workContent').hide();

$('.containerGrid').click(function() {

  $('.workContent').hide();
  var idProject = $(this).parent().attr('data-content');
  $(idProject).show();

});
body {
  margin: 0;
  padding: 0;
}

.container {
  border: 1px solid #ff0000;
  margin: 0;
  padding: 0;
}

ul {
  padding: 0;
  margin: 0;
}

li.grid {
  display: inline-block;
  margin: 0;
  padding: 0;
  width: 20%;
  height: 200px;
  float: left;
  vertical-align: top;
  background-color: #00ff24;
}

li.grid:hover {
  background-color: #99f4a6;
}

.containerGrid {
  width: 100%;
  height: 200px;
}

.containerGrid h2 {
  padding: 0;
  margin: 0;
}

.workContent {
  height: 500px;
  border: 1px solid #000;
  width: 100%;
  position: absolute;
  left: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <ul>
    <li class="grid" data-content="#project1">
      <div class="containerGrid">
        <h2>Title grid</h2>
      </div>
      <div id="project1" class="workContent">
        <p>Content 1</p>
      </div>
    </li>
    <li class="grid" data-content="#project2">
      <div class="containerGrid">
        <h2>Title grid</h2>
      </div>
      <div id="project2" class="workContent">
        <p>Content 2</p>
      </div>
    </li>
    <li class="grid" data-content="#project3">
      <div class="containerGrid">
        <h2>Title grid</h2>
      </div>
      <div id="project3" class="workContent">
        <p>Content 3</p>
      </div>
    </li>
    <li class="grid" data-content="#project4">
      <div class="containerGrid">
        <h2>Title grid</h2>
      </div>
      <div id="project4" class="workContent">
        <p>Content 4</p>
      </div>
    </li>
    <li class="grid" data-content="#project5">
      <div class="containerGrid">
        <h2>Title grid</h2>
      </div>
      <div id="project5" class="workContent">
        <p>Content 5</p>
      </div>
    </li>
    <li class="grid" data-content="#project6">
      <div class="containerGrid">
        <h2>Title grid</h2>
      </div>
      <div id="project6" class="workContent">
        <p>Content 6</p>
      </div>
    </li>
    <li class="grid" data-content="#project7">
      <div class="containerGrid">
        <h2>Title grid</h2>
      </div>
      <div id="project7" class="workContent">
        <p>Content 7</p>
      </div>
    </li>

  </ul>

</div>

Answer №1

Here are the steps to achieve responsive behavior:

  • Set the parent container with display:flex; flex-wrap: wrap;
  • Use a combination of while loop and .next() function to navigate through sibling elements after the clicked item ($(e.target)) until you reach the start of a new row (you can use .position() for this) or determine if you are at the last row of children
  • Once you reach the first item of the next row, insert a div before it with flex-basis: 100%;. You can either clone content from the clicked div or generate it dynamically.
  • Make sure to remove any previously inserted "big" items (flex-basis:100%) when adding a new one
  • Consider handling the case where you are at the last row (no more siblings to move to a new row).

I will provide further guidance on refining these steps and point out any mistakes made. I encourage you to give it a try and showcase your approach. Learning and improving is key, and remember that console.log() is a helpful tool.


$('.expandables').on('click', '.item', function(e){
  // Remove any open items
  removeItem($('.expandables>.content'));

  var item = $(e.target).closest('.item'), 
      content = item.find('.content'), 
      nextItem = item.next(), 
      nextItemPosition = nextItem.position(); 
  while (nextItemPosition && (nextItemPosition.left > 20)) {
    nextItem = nextItem.next();
    nextItemPosition = nextItem.position();
  }

  if (nextItem.is('.item')) {
    content.clone().insertBefore(nextItem);  
  } else {
    content.clone().appendTo($('.expandables'))
  }
})
function removeItem(item) {
  item.remove();
}

$(window).on('resize', function(){
  removeItem($('.expandables>.content'));
})
.expandables {
  display: flex;
  flex-wrap: wrap;
  list-style-type: none;
  position: relative;
}

.expandables > div {
  flex-basis: calc(25% - 1rem);
}

/* Media queries for different screen sizes */
@media (max-width: 991px) {
  .expandables > div {
    flex-basis: calc(33.33% - 1rem);
  }
}
@media (max-width: 767px) {
.expandables > div {
    flex-basis: calc(50% - 1rem);
  }
}
@media (max-width: 539px) {
  .expandables > div {
    flex-basis: calc(100% - 1rem);
  }
}
.expandables > div > .content {
  display: none;
}
.expandables > .content {
  flex-basis: calc(100% - 1rem);
}

/* Additional styling for visual presentation */
body {margin:0;} *{box-sizing: border-box;}
.expandables {
  padding: .5rem;
}
.expandables>div {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 1px solid #ccc;
  margin: .5rem;
}
.expandables>.content {
  background-color: #787878;
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="expandables">
  <div class="item">
    <div>
      <h2>Title grid 1</h2>
    </div>
    <div class="content">
      <p>Content 1</p>
    </div>
  </div>
  <!-- Additional .item elements omitted for brevity -->
</div>

To see the final version with open/close animations included, visit this link.

It's recommended to run the CSS through an autoprefixer before deployment for better browser compatibility. For maximum compatibility, set it to support versions greater than 0% in the autoprefixer settings box.

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

Issue with carousel functionality being disrupted by resizing of the window

I have lined up a series of 3 divs floating to the left in a straight line, each spanning the width of the page. Here is an example of the HTML structure: <div class="Horizontal-Wrapper"> <div class="Horizontal-Section"> <div ...

bootstrap for a responsive full-screen background image

I'm new to utilizing Twitter's Bootstrap. I am curious about the HTML layout required for implementing a full-screen responsive background image with Bootstrap. Currently, I am using the following mockup: <div class="container-fluid"> &l ...

Tips for creating responsive Math Latex

Check out this link to my website page. Also, take a look at this other link. While using Bootstrap, I've noticed that all content is responsive except for the equations in the first link and the Matrix multiplication example in the second link towar ...

The issue of Bootstrap 4 fixed position not working with inherited width

Exploring content and sidebar: .border { border: 1px solid black; } <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device- ...

The JavaScript functions are not loading within the onload event handler

I've got an HTML document that contains some Script sections. I've consolidated all the functions within a single Script Tag. Now, I want to be able to utilize these methods in both the onload and onclick events. Below is the HTML file with all t ...

Optimal method for sending FQL response to cakephp controller using jQuery

My FQL result is a JavaScript object with the following structure: [{"name":"3904","fql_result_set":[{"like_count":"0"}]},{"name":"7617","fql_result_set":[{"like_count":"0"}]},{"name":"9674","fql_result_set":[{"like_count":"0"}]}] I am struggling to pass ...

Having trouble loading JSON data into jqGrid on a Spring 3 MVC application

How can I load a jqgrid with JSON data type on button click? I have tried various methods but the grid remains empty. What am I missing here? My Grid $("#bedata").click(function(){ jQuery("#list2").jqGrid({ url:'/mso/interop/interopcompa ...

AJAX response not rendering on the webpage

In summary, my goal here is to achieve the following: When an option is selected from a dropdown list within index.php, a function with the onchange="displayData(this) event inside <select> is triggered This function initiates an AJAX POST request ...

Retrieve the value of EJS depending on the JavaScript variable

I am in the process of developing a website for booking appointments using Express, EJS, and MongoDB. When a request is made to '/booking', the book page appears displaying all details about the doctor. Upon clicking the book button next to each ...

What measures can be taken to avoid form submission during the user availability check procedure?

Currently, I have a registration form in place where user availability is being checked using jQuery. However, if the user is not available, I want the form to prevent submission. I am struggling with preventing it from being submitted in the case of unava ...

The model binder fails to bind my model class by default

I am facing an issue with utilizing the Default Model Binder functionality in ASP.NET MVC 2 while trying to create a post... Upon clicking the checkout button, I dynamically populate a form using jQuery code and then proceed to submit it to the server. He ...

When a JavaScript code snippet is pasted within a <pre> tag, it will

I've been attempting to insert a JavaScript code snippet into a specific <div>. Even after wrapping the code in pre and code tags, the code ends up being executed when I try to run it. This outcome is definitely not what I had in mind. ...

Encountering a 404 error in Codeigniter when making an AJAX call

After successfully implementing an upload form with ajax, I encountered some issues when attempting to delete uploaded photos. Initially, I received a "csrf protection error," which led me to disable csrf protection, only to then encounter a "404 not found ...

Transmitting an array through ajax to Django

I'm currently attempting to utilize Ajax in sending a JavaScript array to Django. Here's how I've set it up. main.html: <a href=#>Click</a> <script> $(document).on('click', 'a', function() { var ar ...

Tips for adjusting the value of a textbox up and down

I am facing an issue with my booking flight form that is supposed to take input from users regarding the number of travelers. I have three textboxes for Adult, Children, and Infants respectively, along with a main textbox to display the final result. Howev ...

I'm experimenting with crafting a new color scheme using MUI, which will dynamically alter the background color of my card based on the API

I am attempting to create a function that will change the colors based on the type of Pokemon. However, I'm not sure how to go about it. Any suggestions or ideas!? Check out where I'm brainstorming this logic [This is where the color palette sh ...

What is the best way to insert a video as the background of a section in HTML Bootstrap while also reducing its opacity?

`Hello everyone! I'm diving into coding and creating my own website for the first time. I've managed to put together a decent site, but now I want to take it up a notch by adding video backgrounds that adjust automatically based on the device. B ...

Should commas be used in variables?

Could this be converted in a different way? $('#id').testfunction({ 'source' : [ {'source':'pathimage.jpg','title':'Title 1','description':'This is a description 1.'}, ...

Collecting values using AJAX in Codeigniter from an input file

I have been exploring examples of AJAX code, and I noticed that when using form-data in AJAX, we need to serialize each element individually. While normal data serialization works fine, I encountered an issue when trying to pass the value of an input file ...

Achieving success by correctly reaching the window's edge during an event (onscroll)

This happens to be my 1st inquiry. Specifically, I have a navigation menu with a transparent background and I am attempting to alter the background once it reaches the top edge of the window. window.addEventListener("scroll", navSticky); function navSt ...