Mr_Yoshi
Mr_Yoshi

Reputation: 13

Why modal appears and then disappears?

I've made pretty simple modal code with minimum of JS I think. When button is pressed, modal appears for a second that page refreshes and modal disappears. I've no clue what may be wrong. Thanks in advance!

https://jsfiddle.net/wj3r2qzu/

var modalBtn = document.querySelector("#modal-btn");
var modalBg = document.querySelector(".modal-bg");
var modalClose = document.querySelector(".modal-close");

modalBtn.addEventListener("click", function() {
modalBg.classList.add("bg-active");
});

modalClose.addEventListener("click", function() {
modalBg.classList.remove("bg-active");
});

Upvotes: 0

Views: 160

Answers (2)

osmar reyes
osmar reyes

Reputation: 29

As Anurag said, that button is by default type="submit", that inside a form will try to redirect, another thing that you can do in your js is prevented the default behavior for that button.

modalBtn.addEventListener("click", (ev) => {
	ev.preventDefault();//you can prevent the default action for that button
  modalBg.classList.add("bg-active");
});

Hope this can be helpful.

Upvotes: 1

Anurag Srivastava
Anurag Srivastava

Reputation: 14413

Add a type="button" to your sign up button.

<button class="primary-btn" type="button" id="modal-btn">Sign Up</button>

By default, button inside form is of type="submit", so when you click it, the form is being submitted.

JSFiddle

Upvotes: 2

Related Questions