jonmrich jonmrich -4 years ago 111
Javascript Question

Show bootstrap modal only if URL has certain parameters

Is there a way using Bootstrap's modal functionality to evaluate the URL for parameters and open the modal automatically?

For example:

Visitors to the site with URL :

example.com
don't see the modal. They just see the regular site.

Visitors to the site with URL
example.com?offer=1234
or
example.com/offer1234
see the regular
example.com
site, but with a special modal over the top when the page loads.

Can't figure out any way to do this.

Answer Source

Yes, of course this is possible by only running some JavaScript code if the query string (offer=1234) or URL (/offer1234) matched.

Insert this javascript code somewhere after the div where your modal is declared, typically best to add just before your ending </body> tag:

<script type="text/javascript">
var url = window.location.href;
if(url.indexOf('?offer=1234') != -1 || url.IndexOf('/offer1234') != -1) {
    $('#myModal').modal('show');
}
</script>

You can tweak the if statement however you like, exclude only one statement either side of the double pipe symbols || (OR) if you only want to test one of those url patterns, and where myModal defines a div with your modal content to display (eg. <div id="myModal"></div>).

See the documentation for more options and guidelines. http://getbootstrap.com/javascript/#modals-options

Update I have also put together a working Plunker for you demonstrating: http://run.plnkr.co/yEBML6nxvxKDf0YC/?offer=1234

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download