Joining Modal Bootstrap with HTML5 History API

Asked

Viewed 374 times

3

There is a way to join the modal from Bootstrap (any version) with the API History?

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

I don’t have codes yet because it will be for some future projects.

Example: http://poracaso.ocponline.com.br/ ( Open any post from the list. )

  • 1

    Question... why, reason or circumstance has to change the URL when opening the modal?

  • I updated the post with an exact example, check out friend.

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: I forgot to remove/modal-open when closing.

  • This will be used in projects on the Wordpress platform, I will test today, hugs and thanks.

1

Well, I think setting an example would take a long time, but I’ve done something like this and I can help you with logic.

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

After that you have to create a function that reads the URL normally with the attributes of document.location. This function must read the URL and will be responsible for executing each action referring to the URL, like opening a modal for example.

After creating the function, it should be executed on page loading and on each URL exchange by pushState, for this you can call her in the events window.onload and window.onpopstate.

Observing:

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

2 - The pushState which I was referring to is the function to change the URL if redirecting the page.`

The logic I used was this.

  • Yes, this logic is good, will be used to open posts in Wordpress, it simplifies/changes something in its logic?

  • Just change the question that you don’t need to touch .htaccess, you can use query vars... functions.php rules specific to your need. Just a minimal knowledge of regular expressions. These links can help you: http://codex.wordpress.org/Rewrite_API/add_rewrite_rule and http://wordpress.org/support/topic/how-to-pass-value-in-wordpress-url

  • I think that actually makes it a lot easier! Query vars is a very simple way to work with this logic, I use it to create navigations with history API for one pages in Wordpress.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.