3

I use a modal I got from w3school and I modified it to put several modals on the same page.

I would like to know if I can make these modals generate their own links. Example: I open modal 4 and the page link will change to mywebsite.com/modal4

The code I use is more or less like this

JS

// Get the modal
var modal = document.getElementsByClassName('modal');

// Get the button that opens the modal
var btn = document.getElementsByClassName("myBtn");


// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close");

// When the user clicks the button, open the modal 
btn[0].onclick = function() {
    modal[0].style.display = "block";
}

btn[1].onclick = function() {
    modal[1].style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span[0].onclick = function() {
    modal[0].style.display = "none";
}

span[1].onclick = function() {
    modal[1].style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

HTML

<h2>Modal Example1</h2>

<!-- Trigger/Open The Modal -->
<button id="myBtn" class="myBtn">Open Modal1</button>

<!-- The Modal -->
<div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">×</span>
    <p>Some text in the Modal..1</p>
  </div>

</div>


<h2>Modal Example2</h2>

<!-- Trigger/Open The Modal -->
<button id="myBtn" class="myBtn">Open Modal2</button>

<!-- The Modal -->
<div id="myModal2" class="modal">

  <!-- Modal content -->
  <div class="modal2-content">
    <span class="close">×</span>
    <p>Some text in the Modal..2</p>
  </div>

</div>
Trooller
  • 179
  • 1
  • 2
  • 9

2 Answers2

0

You can change the current URL of the page when opening the modal, as seen in this answer: Modify the URL without reloading the page. To load the modal if you go to mywebsite.com/modal4, you can write some js logic to get the link, see if it addresses a modal, and then open that modal.

You may have to write some backend code to handle links like that, however, you can try to pass link parameters and then use js to parse the parameters out of the link string: How to get the value from the GET parameters?

As JagdeeshKumar pointed out below, you can also navigate to website.com/htmlpage.html#modal4, and you can use js to get that location and load up the modal. See https://www.w3schools.com/jsref/prop_loc_hash.asp

gkgkgkgk
  • 707
  • 2
  • 7
  • 26
0

you can use

your URL will be like root/#modal4window.location.hash = 'something';

Community
  • 1
  • 1
Jagdeesh Kumar
  • 1,640
  • 2
  • 13
  • 29
  • I've tried but couldn't give a link to the modal Would you have a tutorial link teaching this? I'm newbie – Trooller Aug 02 '18 at 19:08