Skip to content

Instantly share code, notes, and snippets.

@MrDys
Created August 29, 2012 13:26
Show Gist options
  • Star 91 You must be signed in to star a gist
  • Fork 18 You must be signed in to fork a gist
  • Save MrDys/3512455 to your computer and use it in GitHub Desktop.
Save MrDys/3512455 to your computer and use it in GitHub Desktop.
Link directly to an open modal window in Bootstrap
/* If you've ever had the need to link directly to an open modal window with Bootstrap, here's a quick and easy way to do it:
Make sure your modal has an id:
<div class="modal" id="myModal" ... >
Then stick this bit of Javascript at at the end of your document:
*/
$(document).ready(function() {
if(window.location.href.indexOf('#myModal') != -1) {
$('#myModal').modal('show');
}
});
/*
Then you can send people to http://www.website.com/page.html#myModal and it'll load the page with the modal open.
*/
@InnoM
Copy link

InnoM commented Mar 19, 2019

Thank you! you helped a lot

@bradley-varol
Copy link

bradley-varol commented Jun 19, 2019

This will work for all modals on your site. Just add the modal name to the url hash (https://example.com?page=1#myModal):

jQuery

$(document).ready(function () {
    $('.modal').each(function () {
        const modalId = `#${$(this).attr('id')}`;
        if (window.location.href.indexOf(modalId) !== -1) {
            $(modalId).modal('show');
        }
    });
});

ES6

const modals = [...document.getElementsByClassName('modal')];
modals.forEach((modal) => {
    const modalId = `#${modal.id}`;
    if (window.location.href.indexOf(modalId) !== -1) {
        $(modalId).modal('show');
    }
});

@AFlorencia
Copy link

Thank you very much!!! You saved my head today!

@callumoberholzer
Copy link

Thanks for this, great fix!

@banagale
Copy link

Thanks Bradley-varol for this useful snippet.

@travisblock
Copy link

thanks

@nmansuri191
Copy link

thanks

@lepastiche
Copy link

OMG! Thanks a lot!

@intelligentpotato
Copy link

intelligentpotato commented Jan 7, 2023

In 2022 you can do:
if (window.location.hash == '#myModal')

@xaledzebari
Copy link

Thats cool bro , thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment