본문 바로가기
정보기술/일반

웹페이지에 단축키 (JavaScript)

by fermi 2008. 7. 19.
http://clien.career.co.kr/zboard/view.php?id=lecture&no=4179

- 대소문자를 구별
- 익스플로러와 파이어폭스에서 정상동작

<script language="JavaScript1.2">

var ar = new Array();

ar[ar.length] = new hotKey("H", "http://domain.com/board/?mid=home");
ar[ar.length] = new hotKey("h", "http://domain.com/board/?mid=home");

ar[ar.length] = new hotKey("F", "http://domain.com/board/?mid=freeboard");
ar[ar.length] = new hotKey("f", "http://domain.com/board/?mid=freeboard");

ar[ar.length] = new hotKey("P", "http://domain.com/board/?mid=photogallery");
ar[ar.length] = new hotKey("p", "http://domain.com/board/?mid=photogallery");

var NS = (window.Event) ? 1 : 0

function checkKey(e) {

    if (e == null) {
    code = event.keyCode;

    if(event.srcElement.tagName == "INPUT" || event.srcElement.tagName == "TEXTAREA") return true;
    }
    else {
        if (e.altKey || e.ctrlKey) {
        return true;
        }

    if(e.target.tagName == "INPUT" || e.target.tagName == "TEXTAREA") return;
    code = e.which;
    }

    key = String.fromCharCode(code).toLowerCase();
    if(code==13) key="enter";

    var code = (NS) ? e.which : event.keyCode;
    var key = String.fromCharCode(code);
    for (var i = 0; i < ar.length; i++) {
        if (key == ar[i].key) location.href = ar[i].url;
    }
}

function hotKey(key, url) {
    this.key = key;
    this.url = url;
}

if (NS) document.captureEvents(Event.KEYPRESS)
    document.onkeypress = checkKey;

</script>