Bootstrap 3.x: how to change the url when a modal trigger is clicked?

Using Bootstrap v3.3.5

I have a webpage that uses a URL domain.com/companies

This is my modality trigger on this web page.

<a href="#modal-add-company" class="btn btn-effect-ripple btn-effect-ripple btn-success" data-toggle="modal"><i class="fa fa-plus"></i> New Company</a>

This will successfully launch this modal

<div id="modal-add-company" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">

However, the URL does not change to domain.com/companies#modal-add-company

Otherwise, the URL domain.com/companies#modal-add-companydoes not trigger a modal reload.

What I need to do to have the following:

  • change the url domain.com/companies#modal-add-companywhenever I run modal and modal, and
  • If I type url directly domain.com/companies#modal-add-company, the modal is displayed
+4
source share
2 answers

jQuery,

$(document).ready(function(){
   $(window.location.hash).modal('show');
   $('a[data-toggle="modal"]').click(function(){
      window.location.hash = $(this).attr('href');
   });
});

, , :

<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>

:

$('button[data-dismiss="modal"]').click(function(){
     var original = window.location.href.substr(0, window.location.href.indexOf('#'))
     history.replaceState({}, document.title, original);
 });

, escape , URL-, :

    $(window.location.hash).modal('show');
    $('a[data-toggle="modal"]').click(function(){
        window.location.hash = $(this).attr('href');
    });

    function revertToOriginalURL() {
        var original = window.location.href.substr(0, window.location.href.indexOf('#'))
        history.replaceState({}, document.title, original);
    }

    $('.modal').on('hidden.bs.modal', function () {
        revertToOriginalURL();
    });

fooobar.com/questions/19071/... , .

+13

onclick ,

onclick="window.location.hash = 'modal-add-company';"

script bootstrap.js

<script>
if(window.location.hash.substr(1) == 'modal-add-company'){
    $('#modal-add-company').modal('show');
}
</script>

.

+1

Source: https://habr.com/ru/post/1619019/


All Articles