JavaScriptで単純なスマートフォン分岐

JavaScriptで単純なスマートフォン分岐。
タブレットはスマートフォン版を表示する場合。

PCからスマートフォンに分岐

if (navigator.userAgent.indexOf('iPhone')>0 || navigator.userAgent.indexOf('Windows Phone')>0 || navigator.userAgent.indexOf('Symbian')>0 || navigator.userAgent.indexOf('BlackBerry')>0 || navigator.userAgent.indexOf('Android')>0 || navigator.userAgent.indexOf('MOBILE')>0){
  setTimeout("link()", 0);
  function link(){
    location.href='/sp/';
  }
}

スマートフォンからPCに分岐

if (navigator.userAgent.indexOf('iPhone')>0 || navigator.userAgent.indexOf('Windows Phone')>0 || navigator.userAgent.indexOf('Symbian')>0 || navigator.userAgent.indexOf('BlackBerry')>0 || navigator.userAgent.indexOf('Android')>0 || navigator.userAgent.indexOf('MOBILE')>0){
}else{
  setTimeout("link()", 0);
  function link(){
    location.href='/';
  }
}

youtubeのAPIがIEの11.0.9600でうまく動作しない問題の解決方法

youtubeのAPIで、
onPlayerReadyやonPlayerStateChangeなどを使ったページを作った時、
IE11の特定のバージョンで動作しなかったので、解決方法を。

html5モードを強制にする

ただし、IE8以前で動作しなくなることが予想されるので、
そこだけは注意が必要。

下記ソース8行目
‘html5’: 1
がミソ。
他の値は全然違うものでも構わない。

  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '390',
      width: '640',
      videoId: 'M7lc1UVf-VE',
      playerVars: {
        'html5': 1
      },
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

参考ページ

http://stackoverflow.com/questions/25041745/youtube-iframe-api-onstatechange-not-firing-in-firefox

どうやって判明したのか?

まずは、該当の動かないブラウザで、
下記ページにアクセスする。
https://www.youtube.com/html5
「html5プレイヤーを利用する」
を選択する。

これで、問題があるページの不都合が解決したので、
yotubeの一部APIは、html5プレイヤーでないと正確に動作しないのだろうと当たりをつけた。
問題が起こるバージョンののIEにおいて、
何も設定しないとデフォルトプレイヤーを利用する設定になっているのではないか?
ということで、強制的にhtml5モードを有効にする方法を探したら前述の結果になった。

スマートフォンでテキストエリアをフォーカスしたら中身を選択済みにする

こういうの、PCではあるけどスマホでは見当たらない。
http://tmlife.net/programming/javascript/textarea-all-select.html

と思ったら、ソーシャルゲームの友達募集ページでは実装されてた。
http://pazudora-friend.com/che/

<input type="text" name="fbshare" onfocus="this.selectionStart=0; this.selectionEnd=this.value.length;" onmouseup="return false" value="自動で選択できます。">

動作確認結果

機種によって不安定なので、その旨クライアントさんに伝える必要あり。

■選択できたりできなかったり
iOS8.4safari

■選択されない(普通に選択はできる)
Android4.2 標準ブラウザ

■使いやすい
Android4.2 Chrome

別窓を開いてシェアしつつ、元々の窓ではシェアありがとう画面を表示する

<a href="https://www.facebook.com/sharer/sharer.php" target="_blank" class="shareBtn">Facebookでシェアする</a>
<a href="https://twitter.com/share?text=share!" target="_blank" class="shareBtn">Twitterでシェアする</a>
$(function(){
	$('.shareBtn').on('click', function(event) {
		window.location.href = 'thanks.html'
	});
});

JavaScriptでスマホサイトの振り分け

indexページのみスマホサイトの振り分けをする、ということをたまにやるので、その方法のメモ。

<script type="text/javascript">
(function () {
	var url = window.location.href;
	var urllast = url.substr((url.length-1));

	if(urllast == '/'){
		url = url + 'sp/';
	}else{
		url = url + '/sp/';
	}

	function link(){
		location.href=url;
	}

	if (navigator.userAgent.indexOf('iPhone')>0 || navigator.userAgent.indexOf('Windows Phone')>0 || navigator.userAgent.indexOf('Symbian')>0 || navigator.userAgent.indexOf('BlackBerry')>0 || navigator.userAgent.indexOf('Android')>0 || navigator.userAgent.indexOf('MOBILE')>0){
		setTimeout(link, 0);
	}
}());
</script>

$(document).on(‘click’,’.selector’, function(){}); と $(‘.selector’).on({ ‘click’: function() {} });の違い

var $jqObj = <div class="btn"></div>
$('.box').append($jqObj);

のようにして、
新たに追加した要素に対して。

$(document).on('click','.btn', function(){});

であれば操作できた要素が

$('.box').on({ 'click': function() {} });

であると操作できなかった。
この二点の本質的な違いはなんなんだろ~か。
jQuery読みこめばわかるんだろうなあ。
わかんないけど、そういう事象があるということをメモ。

フッターで停止する追尾メニュー

フッターで停止する追尾メニュー。
jQuery使用(1.7.2と1.9.1では動いた)
但しメニューが縦に長過ぎると見にくいので、ご利用は計画的に!!
(関数名が「オートスクロール」以外になんかいいのないかな。。。)

$(function(){
//追尾メニュー
	var nav = $('#nav');
	var footer = $("#footer");
	var navTop;
	var navBottom;
	var winTop;

	function autoscroll(){
		//後からのコンテンツの追加に対応できるよう常に計算する
		navBottom = footer.offset().top - nav.height();
		winTop = $(this).scrollTop();
		if (winTop >= navTop && winTop <= navBottom) {
			nav.css({
				position: 'fixed',
				top: '0px'
			});
		}else if(winTop <= navTop){
			nav.css({
				position: 'relative',
				top: '0px'
			});
		}else if(winTop >= navBottom){
			nav.css({
				position: 'absolute',
				top: navBottom + 'px'
			});
		}
	}

	window.onload = function() {
		navTop = nav.offset().top;
		autoscroll();
	}

	//スクロールをするたびに実行
	$(window).scroll(function () {
		autoscroll();
	});
});

3月6日追記
スクロールする度にfooter.offset().topを計算し直すように変更しました。
重くなるじゃん!と思ったけど、コンテンツが後から追加された場合に対応せねばならないので。

youtubeで映像を再生して5秒後にシェアボタン表示

youtubeにこんな便利なAPIがあったとは。
iframe 組み込みの YouTube Player API リファレンス
https://developers.google.com/youtube/iframe_api_reference?hl=ja#Playback_status

下記のような機能(関数)を使いました。

動画の再生を開始してからの経過時間を秒数で返します。
player.getCurrentTime():Number

<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>

<script>
	// 2. This code loads the IFrame Player API code asynchronously.
	var tag = document.createElement('script');

	tag.src = "https://www.youtube.com/iframe_api";
	var firstScriptTag = document.getElementsByTagName('script')[0];
	firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

	// 3. This function creates an <iframe> (and YouTube player)
	//    after the API code downloads.
	var player;
	function onYouTubeIframeAPIReady() {
		player = new YT.Player('player', {
		height: '390',
		width: '640',
		videoId: '-PdPCGkaOyM',
		events: {
			'onReady': onPlayerReady,
			'onStateChange': onPlayerStateChange
			}
		});
	}

	// 4. The API will call this function when the video player is ready.
		function onPlayerReady(event) {
		event.target.pauseVideo();
	}

	// 5. The API calls this function when the player's state changes.
	//    The function indicates that when playing a video (state=1),
	//    the player should play for six seconds and then stop.
	var done = false;
	function onPlayerStateChange(event) {
		setTimeout(showTime, 5000);
		function showTime() {
			if (!done) {
				if(5 < player.getCurrentTime()){
					showGood();
					done = true;
				}else{
					setTimeout(showTime, 1000);
				}
			}
		}
	}
	function showGood() {
		$('#shareBox').fadeIn(500);
	}
</script>

<div id="shareBox">
	<!--シェアボタンを入れておきましょう-->
</div>

簡単に間欠処理してイベント負荷を抑制

スクロールに応じてパララックス処理をするなんて時に、
スクロールの度に処理を走らせると、IEでは重くなる。(IE11でも重い)
なので、指定ミリ秒以下の処理は無視するようにした。
間欠処理は、このエントリでもちらっと触れてたな。
jQueryでTwitter用文字数カウント

jQueryを使った場合。

$(function(){
	var timer = null;
	$(window).on('scroll',function() {
		clearTimeout( timer );
		timer = setTimeout(function() {
			//処理内容
		}, 12 );
	});
});

参考サイト様
https://w3g.jp/blog/tools/intermittent_event_load_reduce