js knockout hotkey

Solutions on MaxInterview for js knockout hotkey by the best coders in the world

showing results for - "js knockout hotkey"
Lucia
17 Sep 2020
1/**
2 * Examples: 
3 * - hotkey: 'ctrl+5' -> when control and 5 are pressed the binding element either is clicked or focus (input, select, textarea, .hotkey-focus)
4 * - hotkey: {trigger: 'shift+b} => same as above but with shift and b
5 * - hotkey: 'ctrl+shift+5' -> same as above but also with shift
6 * - hotkey: {trigger: obsHotKey, action: function(element)} => A trigger or action can be an observable as well. action takes a function. If a non function 
7 * is passed in then the default focus or click event is fired
8 * */
9
10ko.bindingHandlers.hotkey = {
11    init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
12        var options = ko.utils.unwrapObservable(valueAccessor());
13
14        if (typeof options === "object") {
15            var trigger = ko.utils.unwrapObservable(options.trigger.toLowerCase());
16            var action = ko.utils.unwrapObservable(options.action);
17        } else {
18            var trigger = options;
19        }
20
21        var shift = trigger.indexOf("shift") > -1;
22        var ctrl = trigger.indexOf("ctrl") > -1;
23        var alt = trigger.indexOf("alt") > -1;
24        var key = trigger.substring(trigger.length - 1);
25
26
27        $(document).on("keydown", function (e) {
28
29            if (e.shiftKey === shift && e.ctrlKey === ctrl && e.altKey === alt && e.which === key.toUpperCase().charCodeAt(0)) {
30
31                // hot key hit
32                if ($(element).hasClass("hotkey-pressed") === true) return;
33                $(element).addClass("hotkey-pressed");
34
35                if (action && typeof action === "function") {
36                    action(element);
37                } else {
38                    //if a input select or textarea lets focus on it
39                    if (element.tagName.toLowerCase() == "input"
40                        || element.tagName.toLowerCase() == "textarea"
41                        || element.tagName.toLowerCase() == "select")
42                        $(element).focus();
43                    else
44                        $(element).click();
45                }
46                e.preventDefault();
47            }
48
49        });
50        //to keep from continuing calling of the hot key
51        $(document).on("keyup", function (e) {
52            $(element).removeClass("hotkey-pressed");
53        });
54    }
55};
56
similar questions
queries leading to this page
js knockout hotkey