Joining Modal Bootstrap with HTML5 History API

3

Is there a way to merge the Bootstrap modal (any version) with the API History ? p>

The logic would look like this: When opening the modal the URL in the navigation bar would change to exemplo.com/modal-aberto and when closing the modal the URL go back to what it was.

I do not have any code yet, because it will be for some future projects.

Example: link (Open any post in the list.)

    
asked by anonymous 27.03.2014 / 04:29

2 answers

3

I've never used Bootstrap before, but I tested the code and it worked fine:

$('#myModal').on('show.bs.modal', function() {
    window.history.pushState(null, null, "/modal-aberto");
});

$('#myModal').on('hidden.bs.modal', function() {
     window.history.replaceState(null, null, "/");
});

Remember to change the selector to select your modal.

Edited: Had forgotten to remove '/ modal-open' when closing.

    
27.03.2014 / 12:48
1

Well, I think setting an example would take a lot of time, but I've done something like that and can help you with logic.

First you need any form of a server language, in the case of PHP you will have to use .htaccess . With it you have to create a rule that redirects all the URL's to the main file, because if the user refreshes the page or enters the URL manually, it will not be considered a pushState , so it will redirect.

After that you have to create a function that reads the normal URL with the attributes of document.location . This function should read the URL and be responsible for executing each action per URL, such as opening a modal for example.

Once the function is created, it must be executed at page load and at each URL exchange with pushState , so you can call it at events window.onload and window.onpopstate .

Note:

1 - If the behavior is better, you can execute the function call as soon as the DOM is ready to loaded.

2 - The pushState to which I referred is the function to change the URL if you redirect the page. '

The logic I used was this.

    
27.03.2014 / 12:49