I am trying to create a function that will call another function (passed as a parameter) if all the required keys are pressed. This is what I have so far:
function multiKeyPress(funcName, parms, key0, key1, key2, key3, key4, key5) {
var down = [];
var noKeys = arguments.length - 2
var args = parms
// for (i = 0; i < noKeys; i++) {
// if (i == noKeys - 1) {
// keyPress += ('down[key' + i + '])')
// } else {
// keyPress += ('down[key' + i + '] && ')
// }
// }
console.log(noKeys)
console.log(args);
switch (noKeys) {
case 1:
$(window).keydown(function(e) {
down[e.keyCode] = true;
}).keyup(function(e) {
if (down[key0]) {
funcName.apply(this, args);
}
down[e.keyCode] = false;
});
break;
case 2:
$(window).keydown(function(e) {
down[e.keyCode] = true;
}).keyup(function(e) {
if (down[key0] && down[key1]) {
funcName.apply(this, args);
}
down[e.keyCode] = false;
});
break;
case 3:
$(window).keydown(function(e) {
down[e.keyCode] = true;
}).keyup(function(e) {
if (down[key0] && down[key1] && down[key2]) {
funcName.apply(this, args);
}
down[e.keyCode] = false;
});
break;
case 4:
$(window).keydown(function(e) {
down[e.keyCode] = true;
}).keyup(function(e) {
if (down[key0] && down[key1] && down[key2] && down[key3]) {
funcName.apply(this, args);
}
down[e.keyCode] = false;
});
break;
case 5:
$(window).keydown(function(e) {
down[e.keyCode] = true;
}).keyup(function(e) {
if (down[key0] && down[key1] && down[key2] && down[key3] && down[key4]) {
funcName.apply(this, args);
}
down[e.keyCode] = false;
});
break;
case 6:
$(window).keydown(function(e) {
down[e.keyCode] = true;
}).keyup(function(e) {
if (down[key0] && down[key1] && down[key2] && down[key3] && down[key4] && down[key5]) {
funcName.apply(this, args);
}
down[e.keyCode] = false;
});
break;
}
}
Near the top of the function I have commented out a loop that would create a string with the necessary keys but I couldnt pass that as a condition because a string will be a truthy value. Therefore I resorted to a long switch statement. This currently works but I was wondering if there was a way to clean it up or if there are any potential problems.
Thanks
You're on the right track, you just need to think about using arrays.
function multiKeyPress(funcName, parms) {
var keysPressed = Array.prototype.slice.call(arguments, 2);
var down = [];
$(window).keydown(function(e) {
down[e.keyCode] = true;
}).keyup(function(e) {
var allPressed = keysPressed.every(function (key) {
return down[key];
});
if (allPressed) {
funcName.apply(this, args);
}
down[e.keyCode] = false;
});
}
That gets any number of keys passed into the function by treating the arguments like an array. Then the keyup handler uses the every method of Array to make sure all of the entries in the array have been pressed.
I should warn you I haven't tested this in a working application, since none was provided, but I'm pretty sure it will function as a replacement.
If you want help with sorting out this string you talk about in the question, do include it in the question, or add a new question specifically about that code.
Related
When I click the Space button (break), it only plays video. It's not stopping with Space.
I don't know what the problem is.
document.addEventListener("keydown", (e) => {
const tagName = document.activeElement.tagName.toLowerCase();
if (tagName === "input") return;
switch (e.key.toLowerCase()) {
case " ":
if (tagName === "button") return;
case "k":
playVideo();
break;
}
});
// Play video function
function playVideo() {
play_pause.innerHTML = "pause";
play_pause.title = "pause";
video_player.classList.add("paused");
mainVideo.play();
}
// Pause video function
function pauseVideo() {
play_pause.innerHTML = "play_arrow";
play_pause.title = "play";
video_player.classList.remove("paused");
mainVideo.pause();
}
play_pause.addEventListener("click", () => {
const isVideoPaused = video_player.classList.contains("paused");
isVideoPaused ? pauseVideo() : playVideo();
});
mainVideo.addEventListener("play", () => {
playVideo();
});
let state = true;
switch (e.key.toLowerCase()) {
case e.keyKode == 32:
if(state == true){
playVideo();
state = false;
} else {
pauseVideo();
state = true;
}
break;
}
}
Try this out for space.
There is correct answer if someones need.
case e.keyCode == 32:
if (mainVideo.paused) {
mainVideo.play();
} else {
mainVideo.pause();
}
break;
Please, I'm trying to choose an option in 'ComboBox', but the "optionElement.Selected = true;" doesn't work. Am I using it the right way? It's necessary make another command before? I have an auxiliary function and a stretch of the main function. Detail: "pdcme_cd_tipo_ac" is a 'TextBox':
// MAIN FUNCTION
// ...
var optionElements = oGecko.Document.GetElementsByTagName("option");
foreach (GeckoOptionElement optionElement in optionElements)
{
//2019-12-06 - Fabio I. - If the combo is "ID = #cd_type" (because it takes ALL options from ALL combos!);
if (optionElement.Parent.Id == "#cd_type")
{
if (optionElement.Label.ToUpper() == "APPLICATION")
{
optionElement.Selected = true;
SetTextInput_ID("pdcme_cd_tipo_ac", optionElement.Label);
break;
}
else if (optionElement.Label.ToUpper() == "TOTAL RESCUE")
{
optionElement.Selected = true;
SetTextInput_ID("pdcme_cd_tipo_ac", optionElement.Label);
break;
}
else if (optionElement.Label.ToUpper() == "REDEMPTION LIQUID VALUE")
{
optionElement.Selected = true;
SetTextInput_ID("pdcme_cd_tipo_ac", optionElement.Label);
break;
}
// ...
}
}
private bool SetTextInput_ID(string ID,
string ValueID)
{
GeckoElement ele;
try
{
ele = oGecko.Document.GetElementById(ID);
if (ele == null) return false;
if (ele.GetType().ToString() != "Gecko.DOM.GeckoInputElement") return false;
((GeckoInputElement)ele).Focus();
((GeckoInputElement)ele).Value = ValueID;
((GeckoInputElement)ele).Click();
return true;
}
catch (Exception ex)
{
return false;
}
}
I've got the following challenge on my website.
Uncaught ReferenceError: resize_cnt is not defined
at loop (main.js:204)
at init.js:201
I've got embedded code on my website that opens modal window and the error only occurs on pages that have that modal included. That embedded code is a designstudio plugin where customer can design their own space and I've added woocommerce functions that collects the samples that customer requested and add them to the woocommerce basket.
// this is the main loop, always running
function loop() {
if (ao.sys.resize_enable == 1) {
if (ao.sys.loading == 0) {
ao.sys.global_loader.deact();
} else {
ao.sys.global_loader.act();
}
refresh_pos_size();
if (typeof (appli_loop) == "function") {
appli_loop();
}
if (typeof (cust_loop) == "function") {
cust_loop();
}
if (typeof (ao.init.orientation_enable) != 'undefined'
&& ao.init.orientation_enable == 1) {
detect_orientation();
}
if (ao.sys.rendering == 0
&& ($(window).height() != ao.sys.current_h || $(window).width() != ao.sys.current_w)) {
ao.sys.current_w = $(window).width();
ao.sys.current_h = $(window).height();
resize_done = 1;
resize_cnt = 0;
if (current_room_id > -1) {
set_display();
}
} else {
resize_cnt++; /** here is where the error occurs **/
}
if ((resize_done == 1) && (resize_cnt > 10)
&& (ao.sys.resize_enable == 1)) {
if (ao.sys.comp_active == 1) {
// btt_left_comp_func();
}
if (typeof (appli_loop_after_resize) == "function") {
appli_loop_after_resize();
}
if (typeof (cust_loop_after_resize) == "function") {
cust_loop_after_resize();
}
resize_done = 0;
resize_cnt = 0;
if (editor_mode != 0) {
scale_to_view();
function init_app() {
ao.sys.init_cnt++;
// alert(ao.sys.init_cnt);
debug.log('init_app: ' + ao.sys.init_cnt + ' / 13');
switch (ao.sys.init_cnt) {
case 1:
load_user();
break;
case 2:
if (ao.cfg.phonegap == 1) {
if (localStorage.getItem("country_" + ao.cfg.app_version) != null) {
ao.sys.current_country = localStorage.getItem("country_"
+ ao.cfg.app_version);
ao.cfg.language = localStorage.getItem("language_"
+ ao.cfg.app_version);
}
checkConnection();
init_db();
} else {
init_app();
}
break;
case 3:
load_language();
break;
case 4:
if (typeof load_catlist == 'function') {
load_catlist();
} else {
init_app();
}
break;
case 5:
load_room_list();
break;
case 6:
if (typeof load_prodlist_egger_vds_online == 'function') {
load_prodlist_egger_vds_online();
} else {
if (typeof load_prodlist == 'function') {
load_prodlist();
} else {
init_app();
}
}
break;
case 7:
init_application();
break;
case 8:
if ((ao.cfg.phonegap == 1)
&& (localStorage.getItem("country_" + ao.cfg.app_version) == null)) {
debug.log('load_settings call');
load_settings();
} else {
init_app();
}
break;
case 9:
if (ao.cfg.phonegap == 1) {
if (localStorage.getItem("country_" + ao.cfg.app_version) != localStorage
.getItem("old_country_" + ao.cfg.app_version)) {
localStorage.setItem("old_country_" + ao.cfg.app_version,
ao.sys.current_country);
debug.log('init_db2 call');
init_db2();
} else {
init_app();
}
} else {
init_app();
}
break;
case 10:
init_startscreen();
break;
case 11:
if (typeof init_appli == 'function') {
init_appli();
} else {
init_app();
}
break;
case 12:
if (typeof init_cust == 'function') {
init_cust();
} else {
init_app();
}
break;
case 13:
ao.sys.loading = 0;
window.setInterval(function() {
loop();
}, 40);
if (ao.sys.phonegap == 1) {
if ((ao.sys.device_plattform == "ios")
&& (ao.sys.device_type == 'phone')) {
window.setTimeout("check_iphone_landscape()", 150);
}
}
if (ao.sys.phonegap == 1) {
if (localStorage.getItem("country") == null) {
load_settings();
}
}
break;
default:
break;
}
}
Any ideas, solutions?
Replace resize_cnt++; with
if(typeof resize_cnt == 'undefined') { var resize_cnt = 0; }
resize_cnt++;
That'll solve your immediate error but you will run into this error elsewhere in your code because you haven't actually declared resize_cnt; anywhere.
Edit: Now that I can see your code, just set var resize_cnt = 0; right at the start of your script outside of any functions to give it global scope.
For best practice I'd probably recommend a recursive call on loop(); where you pass in the resize count, place this right at the end of your function and controlled by a setTimeout there.
Idealy, I would like my little project to have the memory functions M-, M+, MR and MC.
I was thinking of separate functions and variables to hold the M- and M+.
Is this a normal approach or there is a better one ?
Any idea what might be wrong with my script ? if there is something wrong ?
the number-display ID is the actual calculator screen
the code is :
$(document).ready(function(){
var display = "";
var operators = ["/", "*", "-", "+"];
var decimalAdded = false;
$("button").click(function() {
var key = $(this).text();
//update screen by adding display string to screen with maximum 19 numbers viewable
function updateDisplay() {
if (display.length > 19) {
$("#number-display").html(display.substr(display.length - 19, display.length));
} else {
$("#number-display").html(display.substr(0, 19));
}
}
//clear all entries by resetting display and variables
if (key === "AC" || key === "ON" || key === "MC") {
decimalAdded = false;
display = "";
$("#number-display").html("0");
}
else if (key === "OFF") {
decimalAdded = false;
display = "";
$("#number-display").html("");
}
//clear previous character and reset decimal bool if last character is decimal
else if (key === "CE") {
if (display.substr(display.length - 1, display.length) === ".") {
decimalAdded = false;
}
display = display.substr(0, display.length - 1);
updateDisplay();
}
//add key to display if key is a number
else if (!isNaN(key)) {
display += key;
updateDisplay();
}
//check that . is the first in the number before adding and add 0. or just .
else if (key === ".") {
if (!decimalAdded) {
if(display > 0){
display += key;
}
else {
display += "0" + key;
}
decimalAdded = true;
updateDisplay();
}
}
//if key is basic operator, check that the last input was a number before inputting
else if (operators.indexOf(key) > -1) {
decimalAdded = false;
//first input is a number
if (display.length > 0 && !isNaN(display.substr(display.length - 1, display.length))) {
display += key;
updateDisplay();
}
// allow minus sign as first input
else if (display.length === 0 && key === "-") {
display += key;
updateDisplay();
}
}
// calculate square root of number
else if ( $(this).id === "sqrt") {
var tempStore = display.html();
$("#number-display").html(eval(Math.sqrt(tempStore)));
decimalAdded = false;
}
// change sign of number
else if ($(this).id === "plusmn") {
var newNum = display * -1;
$("#number-display").html(newNum);
}
// create memory plus and minus and calculate MR
else if (key === "M-") {
}
else if (key === "M+") {
}
// percentage function
else if (key === "%"){
}
else if (key == "=") {
//if last input is a decimal or operator, remove from display
if (isNaN(display.substr(display.length - 1, display.length))) {
display = display.substr(0, display.length - 1);
}
var calc = display;
calc = eval(calc);
display = String(calc);
if (display.indexOf('.')) {
decimalAdded = true;
} else {
decimalAdded = false;
}
$("#number-display").html(display);
}
});});
One alternative is a switch statement, which would look something like:
switch (key) {
case "M-":
// do stuff
break;
case "M+":
// do stuff
break;
case "%":
// do stuff
break;
case "=":
// do stuff
break;
}
More documentation on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
Is there any way of making this function recursive so that I do not need to create a switch for each length of filter criteria ?
var data = [
{a:'aaa',b:'bbb',c:'ccc',d:'ddd',e:'eee'},
{a:'aaa',b:'bbb',c:'ccc',d:'eee',e:'fff'},
{a:'xxx',b:'bbb',c:'ccc',d:'ddd',e:'fff'}
]
function select(data,where){
return data.filter(function(e){
var k = Object.keys(where);
switch(k.length){
case 1: return (e[k[0]] == where[k[0]]);
case 2: return (e[k[0]] == where[k[0]] && e[k[1]] == where[k[1]]);
case 3: return (e[k[0]] == where[k[0]] && e[k[1]] == where[k[1]] && e[k[2]] == where[k[2]]);
case 4: return (e[k[0]] == where[k[0]] && e[k[1]] == where[k[1]] && e[k[2]] == where[k[2]] && e[k[3]] == where[k[3]]);
case 5: return (e[k[0]] == where[k[0]] && e[k[1]] == where[k[1]] && e[k[2]] == where[k[2]] && e[k[3]] == where[k[3]] && e[k[4]] == where[k[4]]);
}
})
}
var where = {a:'aaa',b:'bbb'}
console.log(select(data,where));
It doesn't need to be recursive (I'm not sure you understand what that means), you just need to loop on the elements in where:
function select(data, where) {
return data.filter(function(e) {
var k = Object.keys(where);
return k.every(function(key) {
return e[key] == where[key];
});
})
}
var data = [
{a:'aaa',b:'bbb',c:'ccc',d:'ddd',e:'eee'},
{a:'aaa',b:'bbb',c:'ccc',d:'eee',e:'fff'},
{a:'xxx',b:'bbb',c:'ccc',d:'ddd',e:'fff'}
]
var where = {a:'aaa',b:'bbb'}
console.log(select(data,where));
Try this code:
function select(data, where) {
return data.filter(function (e) {
for (var key in where) {
if (where.hasOwnProperty(key)) {
if (e.hasOwnProperty(key)) {
if (e[key] != where[key]) {
return false;
}
}
else {
return false
}
}
}
return true;
})
}