Devon Murray Devon Murray - 4 months ago 7
jQuery Question

How can I switch out two divs within one div on a time interval using jQuery?

I am trying to code in a Bandzoogle website, which might be causing errors for this, and I have tried many different ways to get this to work. I have tried changing CSS, showing and hiding objects, but this is the only way that it seems to remotely work. The issue is that when loaded, the divs only switch once or twice, when they should be on an infinite loop. I'm all out of ideas, please help. Keep in mind that not all styles are present, as much of the styling is done through the themes of the website. This is all of the code I have done.



.nextshow {
color:#00000;
-webkit-transition: all 0.3s ease-in-out 0s;
transition: all 0.3s ease-in-out 0s;
text-align: center;
cursor: pointer;
border:solid;
height:150px;
border-color:#747a85;
box-shadow: none;
padding:7px;
}

div.nextshow:hover {
-moz-box-shadow: inset 0 0 20px #b3b3b3;
-webkit-box-shadow: inset 0 0 20px #b3b3b3;
box-shadow: inset 0 0 20px #b3b3b3;
}

.new_album {
color:#00000;
text-align: center;
cursor: pointer;
padding:1px;
display:none;
}

.nextshow_title {
color:#00000;
text-align:center;
padding: none;
}

.nextshowtext2 {
font-size: 200%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="nextshow">


<a href="somelink for show" id="nextshow_title" class="nextshow_title">
<div id="nextshow_title" class="nextshow_title">
<h2 class="nextshowtext1">
This is text
</h2>
<h2 class="nextshowtext2">here is more text
</h2>
</div>
</a

<a href="this is another link" id="new_album" class="new_album">
<div id="new_album" class="new_album">
<h2>
All the text here<br>
</h2>
<h1>is just filler<br>
</h1>
<h2>and is just to show what the code is like
</h2>
</div>
</a>



<script>

$('.nextshow').ready(function() {
setInterval( function() {
$('.nextshow_title').css('display', 'none');
$('.new_album').css('display', 'block');
}, 8000);
setInterval( function() {
$('.nextshow_title').css('display', 'block');
$('.new_album').css('display', 'none');
}, 16000);
});

</script>




Answer

Try the following code:

 var page1=true;
    $('.nextshow').ready(function() {
        setInterval( function() {
          if(page1){
            $('.nextshow_title').css('display', 'none');
            $('.new_album').css('display', 'block');}
          else{

            $('.nextshow_title').css('display', 'block');
            $('.new_album').css('display', 'none');
          }
          page1=!page1;
        }, 8000);
    });

I feel its better to have one interval (for simplicity). All it does is it takes some variable (page1) and toggles it, toggling the visibility of the divs.

Edit: Much Simpler Way

$('.nextshow').ready(function() {
  setInterval(function() {
      $('.nextshow_title').toggle();
      $('.new_album').toggle();
  }, 8000);
});