anoop chandran anoop chandran - 5 months ago 44
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 = '';
$('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
button is clicked? Do i need Ajax to achieve this?


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 = '' + Math.random();