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(/200/300/?random)";
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)";
Share
Improve this question
edited May 8, 2024 at 14:51
VLAZ
29k9 gold badges62 silver badges83 bronze badges
asked May 2, 2018 at 11:30
Alexandru NeculaAlexandru Necula
952 silver badges9 bronze badges
3
|
6 Answers
Reset to default 11Most 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>
The problem you are facing is mostly due to the fact that the URL really does not change. This may:
- Not even trigger a new request from your img tag
- 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()) + ")";
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>
)
}
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>
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)";
https://picsum.photos/200/300/?random
generates a 304 - your code seems to work – mplungjan Commented May 2, 2018 at 11:33