LoginSignup
2
1

More than 3 years have passed since last update.

任意の位置までスクロールすると着火するモーダルウィンドウを作ってみた

Last updated at Posted at 2020-03-07

どんな時に使うの?

例えば,ある程度のページをスクロールしたら広告を打ったり,新規登録をうながしたり.
スクリーンショット 2020-03-07 15.27.21.png

背景

今回,これらのものを作ろうとしても特に良さげな記事が無かったので自作しました.
コピペで使ってOKです.

材料

bootstrap 4系
JQuery

これらのみで簡単に作っていきましょう.

モーダルウィンドウの作成

まずはモーダルウィンドウの表示はbootstrapさんにお願いしましょう

  <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered" role="document">
                  <div class="modal-content">
                    <div class="modal-header">
                      <h5 class="modal-title" id="exampleModalCenterTitle">続きを見るにはログインが必要です</h5>
                      <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                      </button>
                    </div>
                    <div class="modal-body" style="text-align : center ;">
                     <p>他にもログイン特典が沢山</p>
                     <p>あなたの<b>気になる企業</b>を検索!</p>
           <img src="任意" alt="hoge" class="w-100" > 
                    </div>
                    <div class="modal-footer">
                      <button type="button" class="btn btn-secondary" data-dismiss="modal">戻る</button>
                      <a href="/hogelogin"><button type="button" class="btn btn-primary">ログイン</button></a>
                    </div>
                  </div>
                </div>
              </div>

べたっとどこでもいいのでbody内に貼ってください.
imgタグを入れるときは bootstrap classのw-100を使えばレスポンシブで綺麗にできるのでオススメ

着火ボタン設置

次に着火ボタンをおきましょう
これもどこに置いてもOK!

<button hidden type="button" id="chakka"  data-toggle="modal" data-target="#exampleModalCenter">着火</button>

chakkaっていうidのボタンを作ります.
ダサいのでhiddenで隠しておきます.

着火

これをJQueryで着火させます.

          $(window).scroll(function() {
            let nowscroll = $(window).scrollTop() ;
            if(nowscroll>=3200){
              $('#chakka').click();
              $("#chakka").remove() ;
            }
          }) ;

3200px以上でchakkaボタンに着火.
消した後何度もモーダルが出るとウザいのでremove()で一回コッキリに.

僕の場合はtopから3200pxで着火させてますが,例えば


 $(window).scroll(function() {
let nowscroll = $(window).scrollTop() ;
console.log("現在地"+nowscroll)
}) ;

こんな感じで画面スクロールしながらどこで着火させるか見つけると良いですよ.

ログインした人に対してもこれを行うのはナンセンスなので
セッションをif文で見てあげて使いましょう.

2
1
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
2
1