Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 803
jonmrich Avatar asked Jan 22 '15 00:01

jonmrich


People also ask

How do I separate URL parameters?

URL parameters are made of a key and a value, separated by an equal sign (=). Multiple parameters are each then separated by an ampersand (&).

How do I know if a URL has a parameter?

To check if a url has query parameters, call the indexOf() method on the url, passing it a question mark, and check if the result is not equal to -1 , e.g. url. indexOf('? ') !== -1 .

How do I show a Bootstrap modal?

To trigger the modal window, you need to use a button or a link. Then include the two data-* attributes: data-toggle="modal" opens the modal window. data-target="#myModal" points to the id of the modal.

How do I show a Bootstrap modal inside a div?

To show a bootstrap modal inside a div the logic behind the above code is to append the HTML code of the modal as well as the modal-backdrop inside that specific div(blue div whose position is relative) and then making the CSS for modal and modal-backdrop to position:absolute so that the modal and its background gets ...


1 Answers

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

like image 115
GONeale Avatar answered Nov 15 '22 20:11

GONeale