Kevin Doan Kevin Doan - 6 months ago 14
HTML Question

Creating a "Slideshow" effect using JS/jQuery

I'm trying to create a website that's going to be a presentation. I had this idea to make it a slideshow effect using JS. Right now I have some of the functions I want but It's not very clean. The general Idea is that you start the page on the first slide, and when you press space bar it will fade out the slide and fade in the next one. Then when you press space bar on the second page it moves on to the third. So on and so-forth.

I have an example below using JS BIN but the idea isn't implemented very well. If someone could help me flesh it out and make it more functional I would appreciate it very much. Ideally the code will allow me to easily add slides but I can't wrap my head around how to do so. I'm playing with the thought of having either a for loop, switch statement, or something similar that would allow me to do so but I can't nail down which one I need to use exactly. Thanks for taking the time to read this far.

JS BIN EXAMPLE

Answer

You can simplify HTML and CSS a lot, there is no need for css repeating, or using of ids, for the same looking elements:

<div  class="div">IntroPage</div>
  <div class="div">Page0</div>
  <div class="div">Page1</div>
  <div class='div'>
  END
  </div>

CSS:

body{
    font-family: 'apercuregular', arial, sans-serif;
    background-color: #96bff7;
    overflow:hidden;
    position: absolute;
    margin: 0px;
    top:     0px;
    left:    0px;
    width:  100%;
    height: 100%;
    z-index:  10;
}




.div{
    position:absolute;
    width:400px;
    top:170px;
    left:50%;
    margin-left:-26px;
    font-weight:300;
    line-height:110%;
    text-align:justify;
    background-color:#96bff7;

}

And jQuery part, could be more elegant, for sure, but this will work too. Set z-indexes (avoid css repeating), set counter, number of slides, and slide on ENTER click:

   i = 0;
        num_of_slides=4;
    //set z-indexes
        $('.div').each(function(i) {
        $(this).css('z-index',num_of_slides-i);
        });
        $(document).keypress(function(e) {
          if (e.keyCode == 13) {
            if (i <= num_of_slides) {
              i++;
              $('.div').eq(i).fadeIn(2000);
             $('.div').eq(i - 1).fadeOut(2000);
//if you want to go from the slideshow start
              if (i == num_of_slides) {
                i = 0;
                $('.div').eq(i).fadeIn(2000);
              }
            }
          }
        });

Demo: https://jsfiddle.net/tx0p4xge/

Comments