Skip to content

Instantly share code, notes, and snippets.

@aka-z
Forked from MrDys/gist:3512455
Created October 30, 2019 11:04
Show Gist options
  • Save aka-z/e9b7b89762de61f790ef06e8b71964ae to your computer and use it in GitHub Desktop.
Save aka-z/e9b7b89762de61f790ef06e8b71964ae 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.
*/
@aka-z
Copy link
Author

aka-z commented Oct 30, 2019

> $(document).ready(function(){
> 	//Open modal con url
> 	var url      	= window.location.href;
> 	var modal_code 	= getParameterByName("modal",url);
> 
> 	if(window.location.href.indexOf('?modal='+modal_code) != -1) {
>     	$('#myModal'+modal_code).modal('show');
>     	/*Like a query string
> 		http://www.website.com/page.html?modal=1
> 		http://www.website.com/page.html?modal=2
> 		...
>     	*/
>   	}
> }); 
> 
> function getParameterByName(name, url) { //Obtiene un value de un query string
>     if (!url) url = window.location.href;
>     name = name.replace(/[\[\]]/g, "\\$&");
>     var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
>         results = regex.exec(url);
>     if (!results) return null;
>     if (!results[2]) return '';
>     return decodeURIComponent(results[2].replace(/\+/g, " "));
> 
>     /*EJEMPLO
> 	// query string: ?foo=lorem&bar=&baz
> 	var foo = getParameterByName('foo'); // "lorem"
> 	var bar = getParameterByName('bar'); // "" (present with empty value)
> 	var baz = getParameterByName('baz'); // "" (present with no value)
> 	var qux = getParameterByName('qux'); // null (absent)
>     */
> }

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