I can't write a unique javascript that can assign ids to be accessed and displayed by direct links. On the page I have this gallery of images and captions:
<div class="modal-item">
<a onclick="document.getElementById('id001').style.display='block'" class="item-link">
<img class="thumb" src="image001"/>
</div>
<div id="id001" class="modal">
<div class="modal-content">
<img alt="" src="image001big"/>
</div>
<caption></caption>
</div>
</div>
</div>
<div class="modal-item">
<a onclick="document.getElementById('id002').style.display='block'" class="item-link">
<img class="thumb" src="image001"/>
</div>
<div id="id002" class="modal">
<div class="modal-content">
<img alt="" src="image002big"/>
</div>
<caption></caption>
</div>
</div>
</div>
...
But after all my research I only got as far as this and it doesn't work. Also I shouldn't need to despecify the id every time otherwise I fill the page with scripts.
<script type='text/javascript'>
$(document).ready(function() {
if(window.location.href.indexOf('#id0743') != -1) {
$('#id0743').modal('show');document.getElementById('id0743').style.display='block';
}
});
</script>
There is a much easier way to do this. The window already has a built-in object called window.location.hash, which will return #id001 if you go to https://example.net/#id001 Here is MDN's documentation about it.
The hash property of the Location interface returns a USVString containing a '#' followed by the fragment identifier of the URL — the ID on the page that the URL is trying to target.
The fragment is not percent-decoded. If the URL does not have a fragment identifier, this property contains an empty string, "".
Note that I'm manually assigning the ID, but that is alone because I can't get the actual hash from the window.
$(document).ready(function() {
let id = window.location.hash;
id = "#id002";
$(id).css('display', 'block');
});
// Pure JS example
window.addEventListener('load', (event) => {
let id = window.location.hash.substring(1);
id = "id001"
document.getElementById(id).style.display='block';
});
.modal {
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="modal-item">
<a onclick="document.getElementById('id001').style.display='block'" class="item-link">
<img class="thumb" src="https://www.fillmurray.com/200/200" />
</a>
</div>
<div id="id001" class="modal">
<div class="modal-content">
<img alt="" src="https://www.fillmurray.com/2000/2000" />
</div>
<caption></caption>
</div>
<div class="modal-item">
<a onclick="document.getElementById('id002').style.display='block'" class="item-link">
<img class="thumb" src="https://www.fillmurray.com/199/199" />
</a>
</div>
<div id="id002" class="modal">
<div class="modal-content">
<img alt="" src="https://www.fillmurray.com/1999/1999" />
</div>
<caption></caption>
</div>