[2016.1.25] jquery plugin - 단축키 생성 ( easyHotkey ) :: 소림사의 홍반장!

아직 기능은 많이 없고 많이 부족하지만 소스 참고 용도로 사용하시라고 올려봅니다.



// 단축키 세팅
(function($) {
    $.fn.easyHotkey = function(options) 
    {
        var sKeys = {
            "CTRL" : 17, "ALT" : 18, "SHIFT" : 16,
            "ENTER" : 13,
            "SPACE" : 32,
            "TAB" : 9,
            "ESC" : 27,
            "BACKSPACE" : 8,
            "N_1": 49, "N_2": 50, "N_3": 51, "N_4": 52, "N_5": 53, "N_6": 54, "N_7": 55, "N_8": 55, "N_9": 56,
            "A":65, "B":66, "C":67, "D":68, "E":69
        };

        var option = $.extend({

            cssKey : "hotkey_disp",
            shape : "circle",
            bgColor : "#ff0000",
            fontColor : "#ffffff",
            size : "20px",
            side : "left",

            getDiameter : function() {
                return parseInt(this.size);
            },
            getRadius : function() {
                return parseInt(this.size) / 2;
            }
        }, options);

        // 단축키 등록 타겟 엘리먼트 반환 - 추후 기능 확장을 위해 함수로 만들어놓음.
        var $root = $(this);
        var $target = function() {
            return $root;
        };

        // CSS 생성/등록
        var createCSS = function() {
            var css = "<style>."+option.cssKey+" {" +
            "position:absolute;" +
            "font-weight:bolder;" +
            "font-size: " + parseInt(option.getDiameter() * 2 / 3) + "px;" +
            "color:"+option.fontColor+";" +
            "text-align:center;" +
            "line-height:"+option.size+";" +
            "height: "+option.size+";" +
            "width: "+option.size+";" +
            "background-color: "+option.bgColor+";" +
            "-webkit-border-radius: "+option.getRadius()+"px;" +
            "-moz-border-radius: "+option.getRadius()+"px;  " +
            "border-radius: "+option.getRadius()+"px;" +
            "}</style> ";

            $('head').append(css);
        };

        // 단축키 엘리먼트 생성
        var makeHotkey = function(e, text) {
            var obj = e.offset();
            var width = e.width();
            var left = '';

            switch(option.side) {
            case 'left':
                if(width < option.getDiameter()) {
                    left = (obj.left-option.getDiameter())+'px';
                } else {
                    left = (obj.left-option.getRadius())+'px';
                }
                break;
            case 'right':

                if(width < option.getDiameter()) {
                    left = (obj.left+width+option.getDiameter())+'px';
                } else {
                    left = (obj.left+width+option.getRadius())+'px';
                }
                break;
            }

            return $('<div>',{   
                "class": option.cssKey,
                css: {
                    "top": (obj.top-option.getRadius())+'px',
                    "left": left
                },
                text: text
            });
        };

        // 단축키 생성/등록
        var createHotkeys = function() {
            var $hotkeys = $('.'+option.cssKey); 
//            console.log("$hotkeys.length : "+$hotkeys.length);
            if($hotkeys.length) {
                $hotkeys.show();
            }else {
                createCSS();
                $target().each(function(i) {
                    $('body').append(makeHotkey($(this), String.fromCharCode(sKeys.A+i)));
                });  
            }
        };

        // 단축키 숨김
        var hideHotkeys = function() {
            $('.'+option.cssKey).hide();
        };

        // 단축키 제거
        var removeHotkeys = function() {
            var $hotkeys = $('.'+option.cssKey); 
            if($hotkeys.length) $hotkeys.remove();
        };

        // 키를 누를때
        $('body').keydown(function( event ) {
            if( event.ctrlKey && event.altKey ) {

                createHotkeys();

                var indexCode = event.keyCode - sKeys.A;

                if(indexCode >= 0 && indexCode < $('.'+option.cssKey).length) {
                    $target().eq(indexCode).click();
                    hideHotkeys();
                }

                clearEvent(event);
            } 
        });

        // 키가 눌렀다 떨어질 때
        $('body').keyup(function( event ) {
//            console.log("keyup : "+event.keyCode);
            if( event.ctrlKey || event.altKey ) {
                hideHotkeys();
            }
        });

        // 창 크기 변경시 기존 등록된 단축키 제거
        window.onresize = function() {
            removeHotkeys();
        }
    };
})(jQuery);


○ 작동원리


단축키를 자동으로 부여하고 단축키가 눌리면 해당 요소를 찾아 click 이벤트를 발생시킵니다.

따라서 onclick 속성이 존재하는 요소에 적용하시면 됩니다.



○ 사용방법


1. 위의 소스를 js 파일로 저장하여 소스에 추가. (jquery.easyHotkey.js)

2. 사용할 페이지에 선언. ( <script type="text/javascript" src="./jquery.easyHotkey.js" charset="utf-8"></script> )

3. $(사용할요소).easyHotkey 호출하여 사용.

default 적용은 onclick 속성이 있는 모든 요소들에 단축키를 부여합니다.

특정 요소에만 부여하고자 하시면 jquery 선택자로 요소 선택 후 easyHotkey() 적용하시면 됩니다.

예) input type이 button인 요소만 적용하는 경우

  -> $('input[type=button]').easyHotkey();

예) onclick 속성을 가진 모든 요소에 대해 적용하는 경우

  -> $('*[onclick]').easyHotkey();



간단한 사용 예제 및 Demo


다른 카테고리의 글 목록

Dev. 웹/Front-end 웹개발을 위한 codepen 카테고리의 포스트를 톺아봅니다