I've created this two event listening function for my Minesweeper game. When I lose the game, I want to remove the event listeners so that I can't click on the cells after losing. How can I do it?
Thanks
board.oncontextmenu = function(e) {
var cellIndex = e.target.cellIndex;
var rowIndexx = e.target.parentNode.rowIndex;
right_click(rowIndexx, cellIndex);
}
board.onclick = function(e) {
var rowIndex = e.target.cellIndex;
var cellIndex = e.target.parentNode.rowIndex;
console.log("coluna: " + cellIndex + " linha: " + rowIndex);
if (primeira_jogada == 0 ) { timer(); }
if (isBomb(cellIndex, rowIndex) && firstmove == 0) {
moveBomb(cellIndex, rowIndex);
refresh();
}
if (isBomb && primeira_jogada !== 0) {
lose();
//event lister stops here
}
}
Use addEventListener and removeEventListener (https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)
Related
I have tried the code before, but when I hold down W it repeats the code, but I want to so if I hold it down, it will only execute the code one.
window.addEventListener("keydown", checkKeyPressW, false);
var player = document.getElementById("player");
var leftMarginCounter = 0;
var bottomMarginCounter = 0;
var leftMarginCounterToString = "";
function checkKeyPressA_D(keyPressed) {
if(keyPressed.keyCode == "97") {
if(player.style.marginLeft != "0px") {
leftMarginCounter = leftMarginCounter - 1;
leftMarginCounterToString = leftMarginCounter.toString();
leftMarginCounterToString = leftMarginCounterToString + "px";
player.style.marginLeft = leftMarginCounterToString;
}
}
else if(keyPressed.keyCode == "100") {
if(player.style.marginLeft != "1316px") {
leftMarginCounter = leftMarginCounter + 1;
leftMarginCounterToString = leftMarginCounter.toString();
leftMarginCounterToString = leftMarginCounterToString + "px";
player.style.marginLeft = leftMarginCounterToString;
}
}
};
function checkKeyPressW(keyPressedW) {
if(keyPressedW.keyCode == "87") {
console.log("Pressed w");
}
}
JS demo: https://jsfiddle.net/utnqeLmf/1/
Code:
window.addEventListener("keydown", checkKeyPressW, {
once : true
});
From the docs
once A Boolean indicating that the listener should be invoked at most
once after being added. If true, the listener would be automatically
removed when invoked.
EDIT
If you want to avoid continuous key consoling when having the key pressed then change the event to keyup
window.addEventListener("keyup", checkKeyPressW);
There is a property called repeat that returns true if the key is being held down
document.addEventListener('keydown', (event) => {
if(event.repeat) {
// key is being held down
} else {
// key is being pressed
}
});
I have a submit function on a textbox with JavaScript. When the script fires, it checks a Kendo grid for a certain article and adds +1 to its quantity as well as opening the corresponding cell in editing mode. What I want to achieve is that on every submit the timer that starts grid.editCell() will reset its timer.
Currently, the event fires properly. However, the timer doesn't get reset, although the clearTimeout() does work if I just simply start the timer and then clear it right afterwards.
JavaScript:
$('#txtBarcode').submit(function (e) {
var grid = $("#PickListDetailGrid").data("kendoGrid");
var dataSource = $("#PickListDetailGrid").data("kendoGrid").dataSource;
var allData = grid.dataSource.data();
var code = this.value;
var notification = $("#notification").data("kendoNotification");
var timer = null;
clearTimeout(timer);
$.each(allData, function (index, item) {
if (item.ArticleID == code) {
clearTimeout(timer);
timer = null;
if (item.Quantity > item.PickedQuantity && item.PickedQuantity.toString().length < 4) {
var edit = function () {
if (item.PickedQuantity != item.Quantity && timer != null) {
grid.select("tr:eq(" + (index) + ")");
grid.editCell("tr:eq(" + (index + 1) + ") td:eq(" + (5) + ")");
} else {
//do nothing
}
}
item.PickedQuantity++;
item.dirty = true;
dataSource.sync();
if (item.PickedQuantity != item.Quantity) {
console.log("tik tok");
if (timer) {
clearTimeout(timer); //cancel the previous timer.
timer = null;
}
timer = setTimeout(edit, 3000);
} else {
clearTimeout(timer);
timer = null;
}
document.getElementById("txtBarcode").value = "";
} else {
if (item.PickedQuantity.toString().length > 4) {
notification.hide();
notification.show({
message: "Added item"
}, "upload-success");
} else {
notification.hide();
notification.show({
title: "Quantity Error",
message: "You already picked this item to the maximum"
}, "error");
document.getElementById("txtBarcode").value = "";
grid.select("tr:eq(" + (index) + ")");
grid.editCell("tr:eq(" + (index + 1) + ") td:eq(" + (5) + ")");
$('.focus :input').focus();
}
}
}
})
})
You can try delay function like this. The delay function should be outside of the each function.
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
delay(function() {
//do something
}, 3000);
The problem was that var timer = null; had to be outside of the submit function to be properly cleared and set to null before assigning a new setTimeout() to it.
I am trying to make a click send function for my emoticon function but it is not working correctly.
I have created this demo from jsfiddle. In this demo you can se there are four textarea and smiley. When you click smiley then other alert (comments will be come here) changing to (Plese write your comment). What is the problem on there and what is the solution anyone can help me in this regard ?
JS
$('.sendcomment').bind('keydown', function (e) {
if (e.keyCode == 13) {
var ID = $(this).attr("data-msgid");
var comment = $(this).val();
if ($.trim(comment).length == 0) {
$("#commentload" + ID).text("Plese write your comment!");
} else {
$("#commentload" + ID).text(comment);
$("#commentid" + ID).val('').css("height", "35px").focus();
}
}
});
/**/
$(document).ready(function () {
$('body').on("click", '.emo', function () {
var ID = $(this).attr("data-msgid");
var comment = $(this).val();
if ($.trim(comment).length == 0) {
$("#commentload" + ID).text("nothing!");
} else {
$("#commentload" + ID).text(comment);
$("#commentid" + ID).val('').css("height", "35px").focus();
}
});
});
$('body').on('click', '.sm-sticker', function (event) {
event.preventDefault();
var theComment = $(this).parents('.container').find('.sendcomment');
var id = $(this).attr('id');
var sticker = $(this).attr('sticker');
var msg = jQuery.trim(theComment.val());
if (msg == '') {
var sp = '';
} else {
var sp = ' ';
}
theComment.val(jQuery.trim(msg + sp + sticker + sp));
var e = $.Event("keydown");
e.keyCode = 13; // # Some key code value
$('.sendcomment').trigger(e);
});
HTML
At 43 line $('.sendcomment').trigger(e); you trigger keydown event to all textareas. Change it to theComment.trigger(e)
I have a slight problem that I do not know how to approach due to my lack of Javascript experience. Basically I have two or more counters that each count upwards or downwards separately. I want to run a function when all of the counters total value equals to 0
But I do not know how to extract that value from the functions that someone wrote for me.
Here is a jsFiddle for the counters
http://jsfiddle.net/RoryMcCrossan/puJ6G/1015/
jQuery(document).ready(function () {
$('.qtyplus').click(function (e) {
e.preventDefault();
var $container = $(this).closest('.count-container');
var $field = $container.find('input[name=' + $(this).data('field') + ']');
var currentVal = parseInt($field.val(), 10);
if (!isNaN(currentVal)) {
$field.val(currentVal + 1);
} else {
$field.val(0);
}
});
$(".qtyminus").click(function (e) {
e.preventDefault();
var $container = $(this).closest('.count-container');
var $field = $container.find('input[name=' + $(this).data('field') + ']');
var currentVal = parseInt($field.val(), 10);
if (!isNaN(currentVal) && !currentVal == 0) {
$field.val(currentVal - 1);
} else {
$field.val(0);
}
});
});
Many thanks! :)
Firstly we can write a new function which checks all our counters and adds their values together:
function checkCounters() {
var result = 0;
// Loop through each "qty" input element
$('.qty').each(function() {
// Add the value of the input to our result
result += +this.value;
});
if (result === 0)
// Your function should be triggered here
console.log("Result is 0");
else
console.log("Result isn't 0, result is " + result);
}
We can then call this function whenever we update the value of a counter:
...
if (!isNaN(currentVal)) {
$field.val(currentVal + 1);
} else {
$field.val(0);
}
checkCounters();
JSFiddle demo.
I'm trying to bind an onChange event to 7 dropdowns inside a loop. But when any of dropdown changes, the onChange event for the last one is always executed.
$(function () {
for (var i = 1; i <= 7; i++) {
$('select[id$="bodysys' + i + '"]').change(function () {
if (this.value == "99")
enabletextbox($('input[id$="bodysys' + i + 'spec"]')[0]);
});
}
}
How to make onChange work for all elements separately?
This is called the last one only problem, and is solved using a closure:
$(function () {
for (var i = 1; i <= 7; i++) {
(function (i) {
$('select[id$="bodysys' + i + '"]').change(function () {
if (this.value == "99")
enabletextbox($('input[id$="bodysys' + i + 'spec"]')[0]);
});
})(i);
}
}
It creates a new scope, so when i is changed in the original scope, it will not be changed in the old scope.
$('select[id*="bodysys"]').each(function (index) {
$(this).change(function () {
if ($("option:selected", this).val() == "99")
enabletext($('input[id$="bodysys' + (index + 1) + 'spec"]')[0]);
});
});
This way works too.