USer12345
USer12345

Reputation: 39

How can i completely exit a modal after i close it

I have this model in my page which is working fine but when i close it the url still has its name like #modalname. Here is my code:

<script>

var modal = document.getElementById("myModal");
var btn = document.getElementById("adm");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
  modal.style.display = "block";
}
span.onclick = function() {
  modal.style.display = "none";
}
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
} 

</script>

Here is html code:

<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">&times;</span>
              <center>
                <label style="font-size: 25px; color:#2193b0;"><i class="fas fa-lock"></i>Enter Admin Password to access Admin Section</label>
              <br><br>
            <input type="password" id="password" name="" class="input-text"  autocomplete="off" style="width:500px;height: 50px;">
            <br>
            <a href="./admin/index.php" onclick="javascript:return validatePass()"><button class="button" name="check"><span>GO</span></button></a>
            <br></center>

</div>
</div>

Here is how i access the modal:

<li id="adm"><i class="fas fa-lock"></i><a href="#myModal">Admin</a></li>

This is how my url looks after i close it:

http://localhost/project/index.php#myModal

Upvotes: 0

Views: 108

Answers (3)

Alex K
Alex K

Reputation: 183

Would be nice to have a separate functions to open and close the modal,

function openModal() {
  modal.style.display = "block";
}

function closeModal() {
  modal.style.display = "none";
}

So your code with all of the above combined should be smth like this:

// This removes hash
function removeHash() { 
  history.pushState('', document.title, window.location.pathname + window.location.search);
}
    
function openModal() {
  modal.style.display = 'block';
}

function closeModal() {
  modal.style.display = 'none';
  removeHash();
}

var modal = document.getElementById('myModal');
var btn = document.getElementById('adm');
var span = document.getElementsByClassName('close')[0];

btn.onclick = openModal;    
span.onclick = closeModal;    
window.onclick = function(event) {
  if (event.target == modal) {
    closeModal();
  }
} 

Upvotes: 1

btb
btb

Reputation: 180

I wonder why you have to use <a href="#myModal> to open modal, just replace it by button:

<li id="adm"><i class="fas fa-lock"></i><button>Admin</button></li>

If you dont want to use button because it's default style, you can try with <span> tag:

<li id="adm"><i class="fas fa-lock"></i><span style="cursor:pointer">Admin</span></li>

For <a> tag:

<li id="adm"><i class="fas fa-lock"></i><a role="button">Admin</a></li>

Upvotes: 2

Nitheesh
Nitheesh

Reputation: 19986

Add <a href=""></a> to the close button

Upvotes: 0

Related Questions