Rubytastic
Rubytastic

Reputation: 15501

Cycle through a set of multiple images with jquery in an endless loop?

I have this jquery image cycler that does the following:

What would be the best way to cycle through 14 images, getting a random image assigned to each of the 14 divs?

EDIT: AJAX calls like my first solution seems a stupid idea ( high load on server if there are hundreds of pages open ) so precaching seems a better option.

EDIT2: Rewrote the question to be more precise and clear

I found this great method on pre-caching:

  var images = [
    '/path/to/image1.png',
    '/path/to/image2.png'
];

$(images).each(function() {
    var image = $('<img />').attr('src', this);
});

My old current method:

  $("#hi1").load('/get_img');
  $("#hi2").load('/get_img');
  $("#hi3").load('/get_img');
  ... etc till 14

  var refreshId = setInterval(function() {
      $("#h1").load('/get_img');
      $("#h2").load('/get_img');
      $("#h3").load('/get_img');
      }, 4000);
      $.ajaxSetup({ cache: true });
  })

Upvotes: 0

Views: 440

Answers (2)

CWSpear
CWSpear

Reputation: 3270

You could just return the source in the AJAX and create an <img> and set the src, and then if it's not needed, hide it, so if that image gets returned again, you can just unhide it instead of loading it again. You can check to see if the image exists with something like:

$('img[src="' + src + '"]').length > 0;

If that's true, then it exists, so just show it. If not, load the image into the DOM. Just hide images when not needed.

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167250

You can do one thing in your code.

  $("#hi1").load('/get_img');
  $("#hi2").load('/get_img');
  $("#hi3").load('/get_img');

  var refreshId = setInterval(function() {
      $("#h1").load('/get_img').hide().delay(4000).show();
      $("#h2").load('/get_img').hide().delay(4000).show();
      $("#h3").load('/get_img').hide().delay(4000).show();
      }, 0);
      $.ajaxSetup({ cache: true });
  })

So once the dom is ready, it loads the images, and immediately hides it. Then after a delay(4000) delay of 4 seconds, it shows the contents.

Upvotes: 1

Related Questions