How to refresh part of a page (div) with JavaScript?

Spread the love

Sometimes, we want to refresh part of a page (div) with JavaScript.

In this article, we’ll look at how to refresh part of a page (div) with JavaScript.

How to refresh part of a page (div) with JavaScript?

To refresh part of a page (div) with JavaScript, we set the innerHTML property of the div.

For instance, we write

<div id="staticPart">
  Here is static part of page

  <button id="btn" onclick="refresh()">Click here</button>
</div>

<div id="dynamicPart">Dynamic part</div>

to add the elements.

We make the button call the refresh function when we click it by setting the onclick attribute to refresh().

Then we write

const url = "https://example.com";

async function refresh() {
  btn.disabled = true;
  dynamicPart.innerHTML = "Loading...";
  dynamicPart.innerHTML = await (await fetch(url)).text();
  setTimeout(refresh, 2000);
}

to define the refresh function that sets the innerHTML property to the content returned by the promise returned by fetch and text.

We use await to get the promises’ result.

And we call setTimeout to call refresh again after 2 seconds.

Conclusion

To refresh part of a page (div) with JavaScript, we set the innerHTML property of the div.

Leave a Reply

Your email address will not be published. Required fields are marked *