Prevent page to automatically refresh after clicking a button

Generally when we click a Button on our page, button performs ts actions and the page gets reloaded to its original state. To do not refresh the page we add event.preventDefault(); at the end of our JavaScript function.

<button id="myBtn">Try it​</button> 
<p id="demo">
</p> 
<script>
document.getElementById("myBtn").addEventListener("click", function(){
    document.getElementById("demo").innerHTML = "Hello World";
    event.preventDefault();
});
</script> ​<br/>

Another code can be:

<button id="myBtn" onclick="test()">Try it​</button>
<p id="demo"> 
</p>
<script>
function test(){
    document.getElementById("demo").innerHTML = "Hello World";
    event.preventDefault();
}
</script> ​​<br/>
Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started