简体   繁体   中英

How to make an image display on first page load, but not subsequent loads

I am running three photos in a js slideshow function, and I'm wondering if it's possible to have the first image in the slideshow display only when the side is FIRST loaded, but not when an user navigates to other pages in the site. If possible, I would like subsequent page loads to begin at the second or third image in the slideshow.

$(document).ready(function(){


  $(function () {
    setTimeout(playSlideShow, 6400);

  function playSlideShow() {

    var currImgContainer = $('.showImg');
    if (!$(currImgContainer).hasClass('lastImg')) {
        $('.showImg').removeClass('showImg').next().addClass('showImg');
        setTimeout(playSlideShow, 6400);
    }
    if (!$(currImgContainer).hasClass('secImg')) {
        setTimeout(playSlideShow, 4500);
    }
   }
 });
});

HTML:

<div class="slideShow" id="slideshow">
   <div class="showImg">
     <img src="img1.gif" />
   </div>
   <div class="secImg">
     <img src="img2.gif" />
   </div>
   <div class="lastImg">
     <img src="img3.gif"/>
   </div>
</div>

Storing data in the browser from previous page loads is pretty complicated and time consuming for a task like this.

Another option would be to set the carousel to display a different image based on which page it's being loaded on.

First, you can add a data attribute to a consistent element in each of your pages like this:

  <body data-slideNum="2">
    <div class="slideShow" id="slideshow">
     <div class="showImg">
       <img src="img1.gif" />
     </div>
     <div class="secImg">
       <img src="img2.gif" />
     </div>
     <div class="lastImg">
       <img src="img3.gif"/>
     </div>
   </div>
  </body>

The, you can write some javascript to check that attribute on page load and set the carousel image number accordingly. Something like this:

var startingSlide = $('body').attr('data-slideNum');

Which, in this case would set 'startingSlide' equal to '2'.

Maybe you could use jQuery Cookie. https://github.com/carhartl/jquery-cookie

On page load, check if the cookie is set, if not display the image and set it, if it is set don't do anything (assuming image is hidden by default).

Something like this:

if($.cookie('image') == undefined)
    $('#image').show();
    $.cookie('image', 'shown');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM