Accessing window.event.altkey in a setInterval - javascript

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.

Related

JavaScript Pass variable event to event listener

I'm working on a canvas paint project and I'm trying to change the event type of an event listener. For example, a user selects (i) Click or (ii) Mouseover. Then "Click" or "Mouseover" are passed as parameters to the event listener. Been scratching my head on it for a day or so. Not sure if the event is immutable. Anyway thought I'd post it. Also, I'm using range as the input (with values of 0 and 1). Any help would be greatly appreciated.
<input type="range" id="state" name="state" min="0" max="1" value="0" onchange="changestate();">
$state = "mousemove"; // Global Variable
function changestate(){
x = document.getElementByID("state").value;
if(x == 1){
$state = "mousemove";
} else {
$state = "click";
}
canvas.addEventListener($state, function (evt) {
//code
}, false);
You might have to do this with two different event listener's, but you can just pass the same function into them and then check with that function whether or not to run code for the mouseover event or click
JS
$state = "mousemove"; // Global Variable
function changestate() {
x = document.getElementById("state").value;
if (x == 1) {
$state = "mousemove";
} else {
$state = "click";
}
}
function doSomething(evt) {
if ($state == 0) {
// put all the code here for click event
} else if ($state == 1) {
// put all the code here for mouseover event
}
}
window.addEventListener('click', doSomething, false)
window.addEventListener('mouseover', doSomething, false)
Ultimately, the following got me what I was looking for. Thank you all for your help.
canvas.addEventListener("mousemove", function (evt) {
var mousestate = document.getElementById("state").value;
if(mousestate == 0){
// code
}
} else {
canvas.addEventListener("click", function (evt) {
//code
}, false);
}
}, false);

Javascript Onkeydown loop till variable = false

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.

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

Restore default value of arrows key

I'm using a script (impress.js) that bins some particular action to keyup and keydown events for left, right, up and down arrows.
In some particular moments (for example while typing in a textarea) I want back the default behaviour for the arrows.
I tried without success with
$("a#show-ta").click( function() {
document.addEventListener("keydown", function ( event ) {
if (event.keyCode >= 37 && event.keyCode <= 40) {
return;
}
});
document.addEventListener("keyup", function ( event ) {
if (event.keyCode >= 37 && event.keyCode <= 40) {
return;
}
});
});
where a#show-ta is the button that shows my textarea.
You want to prevent the keypress from bubbling up to the document where (I assume) Impress binds its handlers:
$("textarea").on('keyup keydown keypress', function(e) {
e.stopPropagation();
});
If you need the event in a specific zone, such as a texarea, you should stop the propagation of the event like this :
$('textarea').keydown( function(ev) {
ev.stopPropagation();
});
If the events are necessary for the whole page but you want to exclude while you are in a textarea, for example, you could raise a flag which you would validate in the event.
var keydownActivated = true;
$('textarea').keydown( function(ev) {
if (keydownActivated) {
ev.preventDefault();
// dostuff
}
});
This will more or less get you where you are going. Create a flag that tracks whether or not the textarea has focus, and check that flag in your current key press event handlers. I can't see all of your code, so this is just a simple example:
var textareaHasFocus = false;
var textarea = document.querySelector('#yourTextarea');
textarea.addEventListener('focus', function(event) {
textareaHasFocus = true;
}, false);
textarea.addEventListener('blur', function(event) {
textareaHasFocus = false;
}, false);
document.addEventListener("keydown", function ( event ) {
if (textareaHasFocus) return true;
// your current keyboard handler
});
document.addEventListener("keyup", function ( event ) {
if (textareaHasFocus) return true;
// your current keyboard handler
});

Trigger an event when the browser back button is clicked

I am trying to run some code when the browser back button is clicked.
How can i found out browser's back button with out changing the browser history?
I tried the code below.
I got an exception in the else block saying: "event is not defined".
window.onunload = HandleBackFunctionality();
function HandleBackFunctionality()
{
if(window.event)
{
if(window.event.clientX < 40 && window.event.clientY < 0)
{
alert("Browser back button is clicked…");
} else {
alert("Browser refresh button is clicked…");
}
} else {
if(event.currentTarget.performance.navigation.type == 1)
{
alert("Browser refresh button is clicked…");
}
if(event.currentTarget.performance.navigation.type == 2)
{
alert("Browser back button is clicked…");
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
use
$(window).on("navigate", function (event, data) {
var direction = data.state.direction;
if (direction == 'back') {
// do something
}
if (direction == 'forward') {
// do something else
}
});
Okay. Besides the fact that you should not initially trigger the event and to .unload = FunctionName and not .unload=FunctionName() and that you need to pass the event-argument I checked the code in the browser.
currentTarget is empty - this totally makes sense as there is no event-target like onclick but it is just the site reloading/unloading.
Please debug the code by yourself by using this and fit it to your needs:
window.onunload = HandleBackFunctionality;
function HandleBackFunctionality(event)
{
console.log(event, window.event);
}
You will see that currentTarget is not set (while event is).
This is the only solution that works for me with IOS safari.
<script>
window.addEventListener( "pageshow", function ( event ) {
var pagehistory = event.persisted ||
( typeof window.performance != "undefined" &&
window.performance.navigation.type === 2 );
if ( pagehistory ) {
// back button event - Do whatever.
}
});
</script>

Categories

Resources