Prevent page refreshing when clicking a button

Cameron Asbury asked on January 13, 2020 20:43

I am creating a popup modal window. I am just using some basic javascript and CSS to complete this task, and that part is working. However when I click the button that will open the modal, the modal opens and I can see the content but then the page refreshes blowing the modal away. I am using normal button html tags not submit tags. How can I prevent this page refresh when clicking the modal button?

Thanks!

Cameron

Correct Answer

Cameron Asbury answered on January 13, 2020 21:49

Update: I was unaware that not typing a button would make it default to a submit action when it is placed inside of a form tag, and since all the content is inside of a form tag it was submitting, I retyped the button to type button and it is working fine now.

0 votesVote for this answer Unmark Correct answer

Recent Answers


Sean Wright answered on January 14, 2020 04:34

@Cameron

If you are building a site with Kentico's Portal Engine technology then every page will be wrapped in a <form> element, since ASP.NET WebForms, the technology Kentico Portal Engine is built on, relies on this to connect front-end (browser) interactions to back-end (server-side) processing.

Your solution is the typical one, however you can also keep the <button id="myButton" type="submit">Submit</button> if you want and intercept the JavaScript event that is emitted when the button is clicked:

document.querySelector('#myButton').addEventListener('click', function(event) {
  event.preventDefault();
});
1 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.