Get new lorem picsum on button click

6.3k Views Asked by At

I write this line of javascript multiple times(on a button click). The problem is that i get a random image first time and then it doesn't change anymore. Any help, please?

document.getElementsByTagName("body")[0].style.backgroundImage = "url(https://picsum.photos/200/300/?random)";
    

6

There are 6 best solutions below

0
gurvinder372 On BEST ANSWER

Most probably the response is getting cached.

You can ensure that a fresh requests is created every time by appending an inconsequential time value as

document.getElementsByTagName("body")[0].style.backgroundImage = "url(https://picsum.photos/200/300/?random&t=" + new Date().getTime() +")";
0
Delvian On

I suspect that it does not work because the URL does not change; hence the browser will not try to retrieve another image. It would probably work (however caching might still be an issue) if you briefly change the background image to an empty string, then add the link again. Like this:

var element = document.getElementsByTagName("body")[0];
element.style.backgroundImage = "";
element.style.backgroundImage = "url(https://picsum.photos/200/300/?random)";
0
mplungjan On

This will work better. You only get ONE redirect when you get the CSS - the browser caches the result. This one will keep the https://picsum.photos/200/300/?random from being cached by the browser. The getDate() returns number of milliseconds since 1970

<button 
onclick='document.getElementsByTagName("body")[0].style.backgroundImage = 
"url(https://picsum.photos/200/300/?random&rnd"+new Date().getTime()+")"' 
type="button">Click</button>

0
Chirag Ravindra On

The problem you are facing is mostly due to the fact that the URL really does not change. This may:

  1. Not even trigger a new request from your img tag
  2. Be served from your browser cache

So odds are, your image does not change.

One way to fix this would be to pass an additional dummy query parameter which changes on each request.

Sample URL: https://picsum.photos/200/300/?random&dummyParam=1 You can increment dummyParam each time so it looks like a new URL to the img tag and the browser.

Sample Code:

var cb = 0;
setInterval(function() {
  document.getElementsByTagName("body")[0].style.backgroundImage = "url(https://picsum.photos/200/300/?random&cb=" + (++cb) + ")";
}, 1000)
img {
  width: 200px;
  height: auto;
}

EDIT:

@mplungjan's answer uses milliseconds since 1970 as the random dummy parameter and this may be better as you don't have to have a separate variable to track the counter.

Sample code:

document.getElementsByTagName("body")[0].style.backgroundImage = "url(https://picsum.photos/200/300/?random&cb=" + (+new Date()) + ")";

0
SnekNOTSnake On

For future googlers!

Other than Date.now(), you can use ID (or loop index) as the t parameter. This is useful for React applications.

const data = [
  { id: 1, text: 'something' },
  { id: 2, text: 'something cool' },
  { id: 3, text: 'and another one' }
]

export default function App() {
  return (
    <div className="App">
      {data.map((item) => (
        <img
          alt={item.text}
          src={`https://picsum.photos/400/200?random&t=${item.id}`}
        />
      ))}
    </div>
  )
}
0
AudioBubble On

Add a click listener to a button, and set the random parameter of picsum.photos to a random number.

document.querySelector("button").addEventListener("click", () => {
  document.body.style.background = 
    `url(https://picsum.photos/200/300?random=${Math.random()})`;
});
<button>
  Click me to generate a new background image
</button>