JavaScript

CODE TIPS

正規表現

if (str.match(/hoge/)) {
  // 正規表現にマッチ
}
if (str.indexOf('hoge') != -1) {
  // 'hoge'に一致
}

if (~str.indexOf('hoge')) {
  // 'hoge'に一致
}

UserAgent

EventListener

Parent window, Child window

JavaScript access from child window to parent window

/* Parent window */
function parentfunc(arg) {
  console.log(arg); // from child
}
/* Child window */
function triggerdfunc() {
  window.opener.parentfunc('from child');
}

高速化

iPhone の Safari でアドレスバーを隠す

window.addEventListener("load", function() {
  setTimeout(scrollBy, 100, 0, 1);
}, false);

Windowサイズ

undefined分岐

if (typeof a === "undefined") {

setTimeout

じつは、setTimeoutはJavaScriptの言語機能ではなくてブラウザ側の機能です。これも一種のイベントコールバックだと考えるとスッキリします。

引数有りのsetTimeout()

setTimeout(function(){
  Fn(arg);
},3000);

タッチパネル対応

var supportTouch  = 'ontouchend' in document;
var EV_TOUCHSTART = supportTouch ? 'touchstart' : 'mousedown';
var EV_TOUCHMOVE  = supportTouch ? 'touchmove' : 'mousemove';
var EV_TOUCHEND   = supportTouch ? 'touchend' : 'mouseup';

$(document).on(EV_TOUCHEND, '#target', function(){ /**/ });

エラー収集

trim

target = target.replace(/(^\s+)|(\s+$)/g, "");
target = $.trim(target);

Form

Hidden field

Keys in Object

var theObj = {a:1, b:2, c:3}
Object.keys(theObj)
=> ["a", "b", "c"]
Object.keys(theObj).map(function(d){console.log(d)})
=> a
   b
   c

incrimental search

function incrimental search (pattern) {
    try {
        var regex = new RegExp(pattern, "i");
        var trs   = document.getElementsByTagName('tr');
        var len   = trs.length;
        for (var i = 0; i < len; i++) {
            var t = trs[i];
            if (t.className == "line") {
                if (t.innerHTML.match(regex)) {
                    t.style.display = "inline";
                } else {
                    t.style.display = "none";
                }
            }
        }
    } catch (e) {
        // 正規表現の文法エラーを無視する
    }
}
<input type="text" name="pattern" onkeyup="grep(this.value)" style="width:10em; border:1px solid #E3E3E3;">

クエリストリングの値を取得

console.time

console.time('label_name');
// ...
console.timeEnd('label_name');
//=> label_name: 4878.077880859375ms