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)";
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() +")";
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With