Home > Software engineering >  How to cycle through div's with javascript while keeping the div's in the same location
How to cycle through div's with javascript while keeping the div's in the same location

Time:11-19

I am using php, sql, html/css, and javascript. Basically I want to only show one div at a time, which I have completed, except once the first div is hidden the next one shows up right below it. Instead I would like it show up all in the same place as you cycle through it. Any idea how I could fix this?

PHP/HTML: (obviously simplified but I don't think more is necessary)

foreach($headers as $header)
{

        $content .= "<div class='main_' id='card'>";
        $content .=  "</div>";
        $content .= "<button class='next'>Next Order</button>";
        echo $content;
}

CSS:

.main_{
  visibility: hidden;
}
.main_.active{
  display:block;
}
var normalDivs = [];
var focusDiv;

function loopThru(){
  focusDiv  =1;
  if (focusDiv > normalDivs.length-1){
    focusDiv = 0;
  }
  $('.main_').each(function(){
    $(this).css('visibility','hidden');
  });
  normalDivs[focusDiv].css('visibility','visible');
}

$(document).ready(function(){
  $('.main_').each(function(){
    normalDivs.push($(this));
  });
  focusDiv = 0;
  normalDivs[focusDiv].css('visibility','visible')
  $('.next').click(loopThru);
  
});

CodePudding user response:

you have two options:

  1. as mykaf commented - you can use display: none; instead of visibility: hidden;.

that will completely remove the div, but you can recreate it when setting the display back to block.

  1. along with visibility: hidden; add position: absolute; that should let the visible div be in the same location as the first one.
  • Related