javascript - Continue with 'next' image using cookies -


i have images saved 'image_1.jpg', 'image_2.jpg', etc. when 'next' button clicked, new image loads. variable name 'rightnow' used increment number , change url in img src attr. trying store value of variable in cookies continues next image load when new session used.

i checked cookie value in browser, getting set fine. when use new session, seems use value '1' variable 'rightnow' , shows first image. what's wrong code? (using jquery cookie plugin v1.3.1)

    $(document).ready(function(){ var highone=9;  var rightnow=$.cookie("mycookieismine"); if (rightnow=='nan') { rightnow=1;}        $("#next-img").click(function(){         rightnow=rightnow+1; if (rightnow>highone) {rightnow=1;};          $(".imga-class").attr('src',"http://example.com/images/image_"+rightnow+".jpg");         starttime = new date().gettime();         var date = new date();         var minutes = 10;         date.settime(date.gettime() + (minutes * 60 * 1000));         $.cookie("mycookieismine",rightnow, { expires: date });        });     }); 

you have bug (or two) on line:

if (rightnow=='nan') { rightnow=1;}  

consider initial case no cookies have been set. variable rightnow null because $.cookie("mycookieismine"); returns null.

null not equal nan, rightnow becomes nan when add 1 it.

change if statement this:

if (!rightnow) { rightnow=1;}  

this works because null falsy in javascript.

there's 1 more problem line:

if (rightnow=='nan') { rightnow=1;}  

let's stored nan cookie. jquery cookies plugin magically turns string 'nan' saved in cookie actual value nan. when compare string 'nan' value nan evaluate false. check out fiddle prints in console see yourself: http://jsfiddle.net/6vmqb/


Comments