Home > Enterprise >  How to change images in flexslider?
How to change images in flexslider?

Time:11-20

I know this is a very basic question but it has me very confused - there's not much documentation that I could find about the flexslider. Also, I'm very new to this language, I'm a C / ASM type person but trying to get a webpage setup. The page is for an internet radio station. The slider is used to show the album covers of the currently playing, next, and later albums. The image names are 'hard-coded' in the slider which is fine if the images don't need to change. The problem is that the images do change every 3 minutes but the browser caches them so even if the image file contents change, the old image data displays.

I spent the last few weeks developing a Windows service that updates the actual image files (Playing.jpg, Next.jpg, etc.) from the SQL database (among other things) only to find out once the slider is initialized, the displayed images don't change.

Anyway, is the slider just used for 'static' images? Any advice as to how to update the images dynamically? php / js?

<li> <img src="Playing.jpg" alt="" >
   <div >
      <h2>Now Playing</h2>
   </div>
</li>

Thank you!

Keeping the filenames the same but changing the image contents makes no difference. What's the general way of changing slider images dynamically? Code snippets would be appreciated.

CodePudding user response:

To avoid the browser cache you can add a random query like that:

PHP:

<li> <img src="Playing.jpg?v=<?php echo rand(); ?>" alt="" >
   <div >
      <h2>Now Playing</h2>
   </div>
</li>

JS:

<li> <img src="Playing.jpg" alt="" id="imageid">
   <div >
      <h2>Now Playing</h2>
   </div>
</li>
<script>
document.getElementById("imageid").src="Playing.jpg?v=" Math.random();
</script>

CodePudding user response:

Mehedi's answer is good but random strings can collide and Math.random() is returning a float, an integer would be better.
So, it is better to use server current UNIX time e.g.:

PHP

<li>
  <img src="Playing.jpg?v=<?php echo time(); ?>" alt="" />
  <div >
    <h2>Now Playing</h2>
  </div>
</li>

JavaScript

document.getElementById("imageid").src = `Playing.jpg?v=${Date.now()}`;
document.getElementById("imageid").alt = `Image Name: Playing.jpg?v=${Date.now()}`;
<li>
  <img src="Playing.jpg" alt="" id="imageid" />
  <div >
    <h2>Now Playing</h2>
  </div>
</li>

However, this is bad for the user as he is always downloading images. The best solution would be to change the filenames from database and pass that data somehow to your code (maybe an API endpoint or something).
Also, since images are changing every 3 minutes, you could set a cookie in localStorage and check with it for intervals of 3 minutes before passing another time in your <img>.

Personally, I would go with an API-approach.

  • Related