Reputation: 39
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">×</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
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
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