reizer
reizer

Reputation: 253

How to Automatically Show/Hide Divs on Page Load?

I'm trying to create sort of slideshow of customer testimonials. On page load, I'd like to show/hide next testimonial every few seconds. I've got example working, but only using click method. Maybe someone could point out how to make this work without click, but rather automatically on page load?

I tried replacing .click with .ready/.load, but nothing happens.

$(function(){
 $("button").click(function(){
        $(this).parent().fadeOut(500).next().delay(500).fadeIn(500);
    });
});
section {
    width: 300px;
    height: 250px;
    background-color: #ADD3C9;
    margin: auto;
    display: flex;
    flex-direction: column;
}
button {
    display: block;
    margin-top: auto;
    margin-right: auto;
    margin-left: auto;
    font-size: 2em;
    padding: 10px;
    margin-bottom: 10px;
}
#p2,#p3,#p4 {display:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="p1">
    <div>Content for  class "1" Goes Here</div>
  <button>Next</button>
</section>

<section id="p2">
    <div>Content for  class "2" Goes Here</div>
  <button>Next</button>
</section>

<section id="p3">
  <div>Content for  class "3" Goes Here</div>
  <button>Next</button>
</section>

<section id="p4">
  <div>Content for  class "4" Goes Here</div>
</section>

Upvotes: 0

Views: 104

Answers (1)

wangdev87
wangdev87

Reputation: 8751

$(function(){
  setInterval(function() {
        $('section:not(#p4)[style*="display: flex"]').fadeOut(500).next().delay(500).fadeIn(500);
  }, 1000);
});
section {
    width: 300px;
    height: 250px;
    background-color: #ADD3C9;
    margin: auto;
    display: flex;
    flex-direction: column;
}
button {
    display: block;
    margin-top: auto;
    margin-right: auto;
    margin-left: auto;
    font-size: 2em;
    padding: 10px;
    margin-bottom: 10px;
}
#p2,#p3,#p4 {display:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="p1" style="display: flex;">
    <div>Content for  class "1" Goes Here</div>
  <button>Next</button>
</section>

<section id="p2">
    <div>Content for  class "2" Goes Here</div>
  <button>Next</button>
</section>

<section id="p3">
  <div>Content for  class "3" Goes Here</div>
  <button>Next</button>
</section>

<section id="p4">
  <div>Content for  class "4" Goes Here</div>
</section>

Upvotes: 2

Related Questions