Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you refresh a background image after the image has changed

I have a project where the user can upload an image and the image will be stored in a MongoDB database. How can I update the background image of a div I have on the page every time a new image is uploaded without refreshing the page? I tried removing the background image and re-adding it, but it didn't seem to work:

function updateLogo() {
    console.log("update");
    $("#chain-logo").css("background-image", "none");
    $("#chain-logo").css("background-image", `url("/api/images/chain/${chainId}")`);
}

Here's the code that sends the image to the server and then calls updateLogo:

function uploadLogo() {
    let file = document.getElementById("logo-input").files[0];
    let formData = new FormData();

    formData.append("logo", file);

    fetch(`/chain/${chainId}/upload/logo`, {
        method: "POST",
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        updateLogo();
    });
}

HTML for the page:

<body>
    <div id="header-container"></div>
    <div id="administrator-message-banner">
        <p></p>
    </div>
    <div id="chain-logo-container">
        <input type="file" id="logo-input" accept=".png,.svg,.jpeg,.gif,.jpg,.txt" />
        <div id="chain-logo"></div>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="/public/js/chain.js"></script>
</body>

CSS for div:

#chain-logo {
    border-radius: 20px;
    height: 200px;
    width: 260px;
    background-image: url("/public/images/chain-default.svg");
    background-size: 260px 200px;
}
like image 964
Illusion705 Avatar asked Nov 06 '22 00:11

Illusion705


1 Answers

Thanks to StackSlave for coming up with this idea!

I was able to fix my problem by changing my code to the following:

// updates logo
let requestNum = 0;
function updateLogo(chain) {
    fetch(`/api/chain/${chainId}/data`)
        .then(response => response.json())
        .then(data => {
            $("#chain-logo").css("background-image", `url("/api/images/chain/${chainId}?requestNum=${requestNum}")`);
        });
}

Each time I called the updateLogo function, I incremented the requestNum by 1 so that the url would be different every time.

like image 58
Illusion705 Avatar answered Nov 15 '22 07:11

Illusion705