LoginSignup
3
3

More than 5 years have passed since last update.

スマホで横画面にしたときだけアラートを出す

Last updated at Posted at 2016-09-21

概要

スマホサイトで、縦画面で使ってほしいときのために、画面が回転して横になったらアラートをだすスクリプトを書きました。

コード

$(document).ready(function(){
    var noMoreAlert = false;
    $(window).bind("load orientationchange",function(){
        setTimeout(checkOrientation,100);
    });

    function checkOrientation(){
        var w = $(window).width();
        var h = $(window).height();
        console.log("w:"+w+" h:"+h);
        if(h<w){
            if(noMoreAlert===false){
                if(confirm("本サイトは、縦向きでの利用を推奨しています。\nこれ以上このメッセージを表示しない場合は「OK」を選択して下さい。")){
                    noMoreAlert = true;
                }
            }
        }
    }
});

動作サンプル
http://jsdo.it/tsunet111/yfKwQ

メモ

  • 古いAndroid も対応する場合は、resize イベントもいれておいたほうがよいです。ただし、新しい機種だと、アラート2回発動します。
  • 実務上は、OS判別をして、タブレット以上のサイズ(あるいはPCのみ)では動作しないようにしたほうがよいかと思います。
3
3
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
3
3