views:

45

answers:

2

1) I have to change images dynamically according to values for every x seconds.

I'm using the following function:

setInterval(function() {
    $("#content").load(location.href+" #content>*","");
}, 5000);

It works fine for updating the value, but the images not getting updated into its position.

2) From the 1st question i want to know whether the jquery and css files included in the head tag will load every x seconds or not. if not how to load?

Please give me the suggestion.

A: 

If you are returning a whole HTML page and returning it into the body of another page, that is a bad idea.

Think about it, your html structure would be something like

<doc type>
<html>
  <head>
  </head>
  <body>
    <div>
      <doc type>
      <html>
        <head>
        </head>
        <body>
          <div>

          </div>
        </body>
      </html>
    </div>
  </body>
</html>

Ideally you should be retuning just the content that is to be displayed, not everything.

If you are just updating images, there usually is no need to make an XHR call. You can just set the image src and force the browser to update that content that way.

epascarello
A: 

Does this need to be done with Ajax at all? How many images are you going to cycle through? If it is only a few, just keep all of the src's on the page and switch the image src attribute periodically. This requires no page reload. You may also want to preload all the images so there is no flicker when changing to the other image. For example:

$(function () {
   var images = ['1.png', '2.png', '3.png'];
   $.each(images, function (index, src) {
      $("<img />").attr('src', src); //preload
   });
   var keep = 1;
   setInterval(function () {
      $("#main_img").attr('src', images[keep]);
      keep++;
      if (keep >= images.length) { keep = 0; }
   }, 5000);
});

Now if you don't want to hard code the image urls in the JS, you can load them initially with a single Ajax request.

I would only recommend using Ajax to do all the work if you are talking about an unpredictable set of images or some massive number of images.

tandu