DS00
DS00

Reputation: 21

Changing the image src without reloading the page

I have faced a little problem and I feel like I'm going into circles. I'm currently working on a project where I need to update the <img> src with different images after some undefined time (so I don't want to reload the images with a time interval and the image source will be different each time). I have 15 images that need to be displayed on the page, so what I want to achieve is when the image source changes in the .html file to automatically updated from the server. Also, I'm updating the .html file in a loop, so for each iteration there is a new image. This sounded pretty straightforward to me but I've stumbled upon few struggles. I know a bit of html and JavaScript but I'm completely new to jQuery and AJAX.

So far I've managed to refresh the image id using jQuery with the .load() method, I also tried using the .attr() but it didn't work for me, I still had to refresh the page to see the image i.e. send a new request from the client. What I want is for the server to make changes on the webpage independently of weather the clients send requests.

My code looks like this now:

    <head>
      <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    </head>
    <body>
      <div id="cofimages">
        <img id="images" src="0.jpg" />
      </div>
      <script>        
        $("#cofimages").load("index.html");
      </script>
    </body>

But now the problem is that the image loads very slowly and the clients requests constantly. Is there any way I can solve this by different methods? Is there anyway I can preload the images so the loading time decreases? Any suggestions/ides/solutions are more than welcomed.

Upvotes: 2

Views: 1623

Answers (3)

user1496463
user1496463

Reputation: 410

https://jsfiddle.net/d5tcq5av/

Is this what you are looking for.

var imageList = [
  "http://www.gstatic.com/webp/gallery/1.jpg",
  "http://www.gstatic.com/webp/gallery/2.jpg",
  "http://www.gstatic.com/webp/gallery/3.jpg",
  "http://www.gstatic.com/webp/gallery/4.jpg",
  "http://www.gstatic.com/webp/gallery/5.jpg",
  "http://www.gstatic.com/webp/gallery/6.jpg",
  "http://www.gstatic.com/webp/gallery/7.jpg",
  "http://www.gstatic.com/webp/gallery/8.jpg",
  "http://www.gstatic.com/webp/gallery/9.jpg"
]
var index = 0;

setInterval(function() {
  document.querySelector("#test").src = imageList[index];
  index++;
}, 5000)
<img id="test" src="" />

Upvotes: 0

Emil
Emil

Reputation: 127

You could have all of the images be display:none, and then .show() and .hide() them when needed.

The problem with this is the additional loading time of 15 images when the site is visited.

Upvotes: 0

mooga
mooga

Reputation: 3317

you can use that but it's based on how you want to trigger the change

$(function(){
  $( "#images" ).load( "ajax/index.html #id_form_the_sended_html" );
});

Upvotes: 0

Related Questions