Javascript Onkeydown loop till variable = false - javascript

Lets say var myVariable = true by default. Now how do i make it that on key press right arrow, this code is executed:
document.write("Right");
And will keep being executed till myVariable = false again...

You can use Jquery to do it easily:
<script>$( "body" ).keydown(function( event ) {
if ( event.which == 39) {
event.preventDefault();
document.write("Right");
}
});</script>

Bind the event keydown to your body element.
var myVariable = true
document.body.addEventListener('keydown', function(e) {
if (myVariable && e.keyCode === 39) {
document.write("Right");
myVariable = false;
console.log('First time!');
}
});
<h1>Click here and then right arrow</h1>

I think what you are looking for is something like this:
let arrowRight = null;
function keyChange(type, event) {
if (type === 'down' && event.keyCode === 39) {
if (!arrowRight) {
arrowRight = setInterval(function() {
document.body.append('right');
}, 500);
}
}
else if (type === 'up') {
if (arrowRight) {
clearInterval(arrowRight);
arrowRight = null;
}
}
}
document.addEventListener('keyup', keyChange.bind(null, 'up'));
document.addEventListener('keydown', keyChange.bind(null, 'down'));
But since I'm adding listeners to document and document.write actually clear the document if the one you're writing on is already closed (loaded) you will have to use another method to write on your document (like document.body.append).
You can read more about document.write here.

Related

How to fix keypress event for enter key that is running a function twice while only being called once

I am creating a tip calculator. I have a button on the page that calculates the tip if you press it or if you press enter on the keyboard. When I press the enter key, the function that calculates the tip runs but then it runs again even though I did not call it again anywhere in my code. The odd thing is, is that the second time it runs, it goes into the variable where the function is stored and runs the function. I don't know why it goes into a variable that wasn't called.
I tried debugging to see if I missed a step and if I called the function twice somewhere, but I didn't.
Here is the keypress event:
document.addEventListener('keypress', function(event) {
if (event.keycode === 13 || event.which === 13) {
calculateTip();
}
Then right after that code is the calculateTip variable:
var calculateTip = function() {
some code that does calculations
}
After the key is pressed, calculateTip is executed, then it goes straight into the above variable to run calculateTip again.
I have my code inside an IIFE. I already tested to see if the code outside of this IIFE affected anything, it doesn't. The 'click' event listener works perfectly and only executes the calculateTip function once.
In this version of my code, calculateTip will print 'test' to the console twice if enter is clicked.
The IIFE:
var controller = (function(calcCtrl, UICtrl) {
var setupEventListeners = function() {
var DOM = UICtrl.getDOMstrings();
document.querySelector(DOM.button).addEventListener('click', calculateTip);
document.addEventListener('keypress', function(event) {
if (event.keycode === 13 || event.which === 13) {
calculateTip();
}
});
};
var calculateTip = function() {
console.log('test')
};
return {
init: function() {
setupEventListeners();
}
}
})(calculateController, UIController);
controller.init();
with jquery you can solve it
$(document).unbind('keypress').bind('keypress', function (e) {
if (e.keycode === 13 || e.which === 13) {
calculateTip();
}
});
Just add event.preventDefault(); inside the callback, it helped me.
document.addEventListener('keypress', function(event) {
if (event.keycode === 13 || event.which === 13) {
event.preventDefault();
calculateTip();
}
}
It's give one time would you please check this out.
<script type="text/javascript">
document.addEventListener('keypress', function(event) {
if (event.keycode === 13 || event.which === 13) {
calculateTip();
}
});
var calculateTip = function() {
console.log("enter clicked");
}
</script>
Try to put the following to your event listener function:
event.stopImmediatePropagation();

addEventListener on keyup javascript once

I want to run countup(); and random(); function after I hit enter on my keyboard. But I wanna make that it's only work for the first time.I mean when first time i hit enter, it will run that function. But if those function already run and I hit enter again, it'll never effect anything.
Here's my code :
addEventListener("keydown", function(e){
if (e.keyCode === 13) {
countup();
random();
}
});
Anyone can help me? Thanks.
Do something like this
// Create a named function as your event handler
var myFunction = function (e) {
if (e.keyCode === 13) {
// Do your stuff here
countup();
random();
// Remove event listener so that next time it is not triggered
removeEventListener("keydown", myFunction);
}
};
// Bind "keydown" event
addEventListener("keydown", myFunction);
Idea is user a global variable, set it after firing event.
var is_fired = false;
addEventListener("keydown", function(e){
if (e.keyCode === 13 && is_fired == false) {
countup();
random();
is_fired = true
}
});
You can make click event listener work only once after trigger it.you just need to add another argument to addEventListener() which is {once:true}and it will work as expected:
addEventListener("keydown", function(e){
if (e.keyCode === 13) {
countup();
random();
}
},{once: true});
Check my question it's similar to your case.
Also you can just use removeEventListener()method but you should defined your Anonymous function before as external function like myKeyPressed() and then inside if condition remove event Listener from your element:
element.removeEventListener("keydown", myKeyPressed);
var is_clicked = false;
addEventListener("keydown", function(e){
if (e.keyCode === 13 && !is_clicked) {
countup();
random();
is_clicked = true;
}
});
There is a removeEventListener function in javascript but it's tricky to implement that inside the function you are calling on addEventListener.
Try this, it worked in jsfiddle.
addEventListener("keydown", function(e){
if (e.keyCode === 13) {
alert("i did it");
this.removeEventListener('keydown',arguments.callee,false);
}
});
You can add a variable to check the status of your keydown.
The first time you use it, set it up to true. So you will only have this function triggered once.
var n = document.getElementById("txtInput"),
r = document.getElementById("result"),
loadFlag = true;
n.addEventListener("keyup", function(e) {
if (e.keyCode === 13 && loadFlag ) {
countup(r);
random(r);
loadFlag = false;
}
}, false);
To add keydown to an element in your HTML code.
element.addEventListener("keydown", event => {
//check if event is cancelable because not all event can be cancelled
if(event.cancelable)
{
//this prevent element from executing the default event when user click
event.preventDefault()
if(event.keycode === 13){ //write your statement here }
}
}
for more https://www.w3schools.com/jsref/event_preventdefault.asp

How to fire one function for two separate events in js?

I have 2 events, a keydown and a click. I would like to put them into a single function and when the function is called, whichever event was fired would do what it's supposed to.
Example:
var close = function () {
$('.alert').remove();
};
$(document).on('keydown', function (event) {
if (event.keyCode === 27) {
//27 = ESC
close();
}
});
$('.alertBG').on('click', function () {
close();
});
I can't think of a way to get the document and .alertBG parts to play nicely. (Fiddle)
Don't. Your functions are too different. You have already factored the reusable parts of them out into a close function that you call from both. This is the best way to do it.
If you really wanted to, then you would have to bind a click/keydown handler to document and test the type of event and the element.
$(document).on("keydown click", function (event) {
if (
(event.type === "keydown" && event.keyCode === 27) || (event.type === "click" && (
$(event.target).is(".alertBG") || $(event.target).parents(".alertBG").length))) {
close();
}
});
As you can see, it's much cleaner just to bind your event handlers separately when there are so many differences between them.
Do you mean something like this?
function handler(event) {
if(event.type === "click") {
close();
} else if(event.type === "keydown") {
if (event.keyCode === 27) {
//27 = ESC
close();
}
}
}
$(document).on('keydown', handler);
$('.alertBG').on('click', handler);
Anything like this ?
function myFunc(method){
if(method == "one"){
// do anything
}
else if(method == "other"){
// do other thing
}
}
$(document).on('keydown', function (event) {
if (event.keyCode === 27) {
myFunc("one");
}
});
$('.alertBG').on('click', function () {
myFunc("other");
});

Accessing window.event.altkey in a setInterval

I have the following code:
function optionkey()
{
e = window.event;
if( e.altKey )
{
return "down";
}
else
{
return "up";
}
}
interval = setInterval(function(){
if( optionkey() == "down" ) {
clearInterval(interval);
alert( 5 );
}
}, 100);
Basically the code should run alert(5) when the user presses the optionkey, but instead I get a load of errors: Uncaught TypeError: Cannot read property 'altKey' of undefined
Can anyone tell me why it does this and how to fix it?
Thanks.
jsfiddle
Please let me know if I have misinterpreted your needs, but if you want an alert to fire when pressing the key you need to create an event listener for onkeydown like so
window.onkeydown = function ( e ) {
if(e.altKey){
alert(5);
}
}
First of all event.altKey can only be detected on keypress (input) events like keydown and keyup. However calling a function from setInterval will not trigger the altkey. You will need to catch that in a event handler and pass it on.
function optionkey()
{
if( window['globalAltKey'])
{
return "down";
}
else
{
return "up";
}
}
interval = setInterval(function(){
if( optionkey() == "down" ) {
clearInterval(interval);
alert( 5 );
}
}, 100);
window.addEventListener("keydown", function(e){
if (e.altKey)
{
globalAltKey = true;
}
else
{
globalAltKey = false;
}
}, false)
Now the interval will still test if the optionkey() will return down or up. Only when the user clicks alt this will fire the alert.
I don't know why you have chosen this approach, you can simply attach a click handler to a button and use the keydown event I provided to check if the alt key is globally pressed.

Toggling a function that depends on a button state?

I'm trying to turn a button-click into a toggle that enables or disables a function, depending on its state. The function allows the enter key to be used for a form submission.
var enterToggle = true;
function enterToggleListener(elem) {
enterKeyPress();
elem.click(function() {
enterToggle = !enterToggle;
console.log('enter-toggle clicked')
if (enterToggle === false) {
console.log('enter toggle false')
// What do I need to add here to stop 'enterKeyPress()'?
} else {
console.log('enter toggle true')
enterKeyPress();
}
});
}
function enterKeyPress() {
$('#noteText').keypress(function(e){
if(e.which == 13){
$('#noteButton').click();
}
});
}
enterToggleListener($('#toggle-button'));
What I don't understand is how to stop the enterKeyPress() function when enterToggle is false. Any suggestions?
EDIT: Cleaned-up code, with #James Montagne's answer added
var enterToggle = true;
function enterToggleListener(elem) {
elem.click(function() {
enterToggle = !enterToggle;
if (enterToggle === false) {
$('#enter-toggle').text('Enter key saves note (OFF)')
} else {
$('#enter-toggle').text('Enter key saves note (ON)')
}
});
}
function enterKeyPress() {
$('#noteText').keypress(function(e){
if(enterToggle && e.which == 13){
$('#noteButton').click();
}
});
}
enterKeyPress();
enterToggleListener($('#enter-toggle'));
function enterKeyPress() {
$('#noteText').keypress(function(e){
if(enterToggle && e.which == 13){
$('#noteButton').click();
}
});
}
You can simply check the value of the variable within your handler. This way you don't need to keep adding and removing the handler as seems to be your current approach.
However, if you must add and remove for some reason, you would use off.

Categories

Resources