LoginSignup
23
23

More than 5 years have passed since last update.

bootstrapのmodalをブラウザの「戻る」で閉じる方法

Last updated at Posted at 2015-06-29

便利だったのでメモします。

方法

modalが表示された時
→ 履歴にmodalのid付きのurlを追加します

modalが閉じられた時
→ urlにmodalのidがあったら、ブラウザの「戻る」を起動します

「戻る」ボタンが押された時
→ modalを閉じます

sample.js
$(function() {

  // modalが表示された時
  $(".modal").on("shown.bs.modal", function() {
    var urlReplace = "#" + $(this).attr('id')
    history.pushState(null, null, urlReplace)
  });

  // modalの閉じる機能が動作した時
  $(".modal").on("hidden.bs.modal", function () {
    if(location.hash == "#" + $(this).attr('id')) {
      history.back()
    }
  })

  // 「戻る」ボタンが押された時
  $(window).on('popstate', function() { 
    $(".modal").modal('hide')
  })

})

modalを重ねて使わないページでは、大体期待通り動作すると思います。
もっと良い書き方がありましたら、教えて頂けると嬉しいです。

以上です。

参考

backbutton close bootstrap modal
How to handle the modal closing event in Twitter Bootstrap?
javascriptまとめ

23
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
23