jquery - Javascript - id's are timestamps, if more than 10 then delete the oldest one -


a bit of tricky one, @ least me. here scenario:

<div id="gifs">  <img src="gif/1.jpg" alt="" > <img src="gif/10.jpg" alt="" > <img src="gif/15.jpg" alt="" > <img src="gif/20.jpg" alt="" > <img src="gif/5.jpg" alt="" > </div>  

everytime user clicks on image, image changes gif , id set timestamp.
issues is, don't want more 4 gifs @ time. means that, if there 4 gifs, next time user clicks, older 1 goes being jpg. how can that?

here jquery far:

$("#gifs img").click(function () {          var original = $(this).attr("src");          var newsrc = original.replace('jpg','gif');         if(!$(this).hasclass('on')){             $(this).attr("src" , '');             $(this).attr("src", newsrc );             $(this).addclass('on');              var t = new date();             var time = t.gettime();               $(this).attr('id' , time);              // here, in each function.  need store timestamp inside array...             $('.on').each(function(e){                  //dif[] = $(e).attr('id');              });              /*var oldest = dif.min();              var oldestsrc = $('#'+oldest).attr("src");              var oldestnewsrc = oldestsrc.replace('gif','jpg');              $('#'+oldest).attr("src",oldestnewsrc); */         } }); 

help appreciated.

i this:

(function () {     // cache images can use them later     var $imgs = $("#gifs img");     $imgs.click(function () {         var $this = $(this);         if (!$this.hasclass("on")) {             // ids of images "on"             var ids = array.prototype.slice.call($imgs.filter(".on").map(function () { return this.id; }));             if (ids.length >= 3) {                 // oldest image sorting ids in ascending order , first                 var $oldest = $("#"+ids.sort()[0]);                 // change oldest image                 $oldest.attr("src", function () { return this.src.replace("gif", "jpg"); });                 $oldest.removeclass("on");             }             // change clicked image             $this.attr("id", new date().gettime());             $this.attr("src", function () { return this.src.replace("jpg", "gif"); });             $this.addclass("on");         }     }); })(); 

the whole wrapped in function not pollute global variable scope.


Comments