anoop chandran anoop chandran - 10 days ago 8
Javascript Question

make new image-request on click

I want to make a request to get a new random image from unsplash link.
I'm not sure if this is the right way, however the concept is whenever the user clicks the button the background image should change. This is my code.

$(document).ready(function() {
var changeImg= function(obj){
var imageSrc = 'https://source.unsplash.com/random/';
$('body').css('background-image', 'url(' + imageSrc + ')');
};
$('#getImg').on("click", changeImg);
}


Currently the image changes only when the page is refreshed. How to make it change every time the
#getImg
button is clicked? Do i need Ajax to achieve this?

Answer

That's happens because browser already has loaded this resource. You should change URL to load new background image.

Try something like this:

var imageSrc = 'https://source.unsplash.com/random/?n=' + Math.random();