The code you tried to use, shown in the question and copied from an issue of the gringo site does not seem to me to be what you need. The code only checks if the browser address bar URL has a hash
specific to trigger a function. What you want is actually simpler, which is to just fire the link with Lightbox2.
This is very simple to do:
Just, after charging the DOM, you fire a .click()
on the Lightbox2 link after a short delay with setTimeout
:
$(document).ready(function(){
setTimeout(function(){
$("#myLightbox").click();
}, 500);
});
Notice I put a delay 500 milissegundos
(or half a second), since the plugin documentation does not inform any callback
when the component was loaded (which would be ideal). Then you can adjust this value to 500
to more or less according to what you think best and that the time is enough for the plugin to have been loaded.
Important:
The event $(document).ready(function(){...
requires that jQuery has already been invoked on the page, otherwise it will result in error. You can replace this line with native Javascript code document.addEventListener("DOMContentLoaded", function(){
if you like.
See working:
$(document).ready(function(){
setTimeout(function(){
$("#myLightbox").click();
}, 500);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.1/css/lightbox.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.1/js/lightbox.js"></script>
<a href="https://www.cleverfiles.com/howto/wp-content/uploads/2016/08/mini.jpg" data-lightbox="image-1" data-title="" id="myLightbox"></a>
Aguarde meio segundo...
Another way is by using setInterval
until the div#lightboxOverlay
is created by the plugin, indicating that it is already ready:
$(document).ready(function(){
var tempo = setInterval(function(){
if($("#lightboxOverlay").length){
clearInterval(tempo);
$("#myLightbox").click();
}
}, 1);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.1/css/lightbox.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.1/js/lightbox.js"></script>
<a href="https://www.cleverfiles.com/howto/wp-content/uploads/2016/08/mini.jpg" data-lightbox="image-1" data-title="" id="myLightbox"></a>
Hello @Sam, thank you so much for the answers and examples, it turned out very good.
– adventistapr