made a function but it's not working - javascript

I have no idea why this is not working....
var changeIdValue = function(id, value) {
document.getElementById(id).style.height = value;
};
document.body.onkeydown = function(e){
if(e.keyCode == 40){
document.getElementById("balklongwaarde").addEventListener("onkeydown", function(){
changeIdValue("balklongwaarde", "60px")});
}
}
Can anybody help me why this is not working......
When I delete the code of the on keydown then the animation works without problems.
But I want that code executed after press on key down......

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();

Qualtrics: using space bar to continue, study autoadvancing on next item if item left unanswered before space bar press

I'm very new to JavaScript, and I'm currently trying to add a custom code to my Qualtrics survey that makes it so pressing the spacebar continues the survey in the "Text/Graphic" question type. I have a code that should be working; however, I'm getting an "Unexpected token (" error.
Here is the code:
Qualtrics.SurveyEngine.addOnload(function()
{
document.addEventListener("keydown", function(e) {
if (e.keyCode === 32) {
function(){
that.clickNextButton();
}
}
}
});`
I also found this answer to a similar question from a couple of years back:
Here is a simplified version that works (updated to hide NextButton):
Qualtrics.SurveyEngine.addOnload(function() {
$('NextButton').hide();
document.on("keydown", function(e) {
if (e.keyCode === 13) $('NextButton').click();
});
});
This code, however, doesn't work at all in my survey (as if it wasn't even there).
Any help is much appreciated, thanks in advance!
____ Edit _____
The code I have now used is the following:
Qualtrics.SurveyEngine.addOnload(function()
{
/*Place your JavaScript here to run when the page loads*/
});
Qualtrics.SurveyEngine.addOnReady(function()
{
/*Place your JavaScript here to run when the page is fully displayed*/
Qualtrics.SurveyEngine.addOnReady(function() {
$('NextButton').hide();
document.on("keydown", function(e) {
if (e.keyCode === 32) $('NextButton').click();
});
});
});
Qualtrics.SurveyEngine.addOnUnload(function()
{
/*Place your JavaScript here to run when the page is unloaded*/
});
The problem I have now is that the study autoadvances the next question whenever I press spacebar before ansewring a previous question.
Example
Question 1: Is the sentence you just saw a sensible continuation for the preceding sentence?
* participant presses space bar before answering the question with F for no and J for yes
* The study reminds the participant that they need to answer the question before proceeding to the next question
* Participant answers the question and the study automatically proceeds to the next question, because answering validates the question
--> the study only lets the participant see the next item for a second, and then autoadvances to the next item without the participant pressing any key.
The code I use for the F + J keys is the following:
Qualtrics.SurveyEngine.addOnload(function()
{
this.hideNextButton();
this.hidePreviousButton();
var that = this;
Event.observe(document, 'keydown', function keydownCallback(e) {
var choiceID = null;
switch (e.keyCode) {
case 74: // 'f' was pressed
choiceID = 2;
break;
case 70: // 'j' was pressed
choiceID = 1;
break;
}
if (choiceID) {
Event.stopObserving(document, 'keydown', keydownCallback);
that.setChoiceValue(choiceID, true);
that.clickNextButton();
}
});
});
I think it doesn't work due to a timing issue. Use addOnReady instead:
Qualtrics.SurveyEngine.addOnReady(function() {
$('NextButton').hide();
document.on("keydown", function(e) {
if (e.keyCode === 32) $('NextButton').click();
});
});
Note: with split screen preview mode you have to click in the window first or it won't recognize the key press.
EDIT:
I couldn't recreate your problem (your code worked as is for me when I tried it). However, try the following. It is cleaner and consistent. If it works be sure to accept the answer.
Space bar question:
Qualtrics.SurveyEngine.addOnReady(function() {
$('NextButton').hide();
if($('PreviousButton')) $('PreviousButton').hide();
var evt = document.on('keydown', function(e) {
if (e.which == 32) { //space bar pressed
evt.stop();
$('NextButton').click();
}
});
});
Yes/No question:
Qualtrics.SurveyEngine.addOnReady(function() {
$('NextButton').hide();
if($('PreviousButton')) $('PreviousButton').hide();
var that = this;
var evt = document.on('keydown', function(e) {
var choiceID = null;
if(e.which == 70) choiceID = 1; //'f' was pressed
else if(e.which == 74) choiceID = 2; //'j' was pressed
if (choiceID) {
evt.stop();
that.setChoiceValue(choiceID, true);
$('NextButton').click();
}
});
});
You need to remove the function() around that.clicknextbutton(), and change that to this. that doesn't make sense unless it is a variable set to the this keyword. The function(){} syntax is used to define an expression in a parameter.
Qualtrics.SurveyEngine.addOnload(function(){
document.addEventListener("keydown", function(e) {
if (e.keyCode === 32) {
this.clickNextButton();
}
});
});

Javascript ALT click on link opens alternative link

I want to be able to open an alternate link when I click by holding down the alt button. I've tried some solutions but they seem to have weird problems. All I want is when clicking to detect if the alt key is held down
function selectlink(selection,alt) {
if (alt key is pressed) {
window.open(alt,'_blank');
} else {
window.open(selection,'_blank');
}
In the body:
Click
Preferably WITHOUT Jquery.
You have to reference the event as a parameter, this will make it possible to check if a key was pressed during the click.
function selectlink(selection, alt, e) {
if (e.altKey) {
alert(alt);
} else {
alert(selection);
}
}
Click
With a little bit of rewriting you can make the link a bit smarter and still have functioning links when javascript is disabled.
function selectLink(e) {
var el = e.target;
if (e.altKey) {
window.open(el.getAttribute("alternative"), '_blank');
e.preventDefault();
}
}
Click
Here's a solution using jQuery. I'll write a solution using pure JS in my lunch break.
https://jsfiddle.net/jotq0atz/2/
X
Here is the js:
$("#x").on('click', function(e){
link = $(e.currentTarget).attr('href');
alt_link = $(e.currentTarget).attr('data-alt-href');
if(e.altKey){
alert("alt was held while clicking");
window.open(alt_link, '_blank');
} else {
alert("alt wasn't held while clicking");
window.open(link, '_blank');
}
});
Here's a solution made by adapting the answer provided in javascript alt key
var altdown = false;
document.onkeydown = KeyCheck;
document.onkeyup = KeyCheck;
function KeyCheck(e)
{
var KeyID = (window.event) ? event.keyCode : e.keyCode;
switch(KeyID)
{
case 18:
document.Form1.KeyName.value = "Alt";
if(e.type == "keydown"){
altdown = true;
}
else if(e.type == "keyup"){
altdown = false;
}
break;
}
}
function selectlink(selection,alt) {
if (altdown) {
window.open(alt,'_blank');
} else {
window.open(selection,'_blank');
}
}
The link opened in dependent on the altdown variable which is true when the alt key is pressed down. A working fiddle can be seen here. https://jsfiddle.net/q5kr9h2o/7/

How to change values of div when press key down

I have made divs in my HTML that I use to draw bars with CSS.
Now I want the to values change when the user presses the down arrow key.
This is my JavaScript:
var changeIdValue = function(id, value) {
document.getElementById(id).style.height = value;
};
window.addEventlistener("onkeydown", function(e){
if(e.keyCode == 40){
changeIdValue("balklongwaarde", "60px");
});
}
I don't understand why this is not working.
I know this has been answered already, but if you want to follow your original idea, here's the correct code (because Mritunjay's answer only works for one usage per page).
var changeIdValue = function (id, value) {
document.getElementById(id).style.height = value;
};
window.addEventListener('keydown', function (e) {
if (e.keyCode === 40) {
changeIdValue('balklongwaarde', '60px');
}
});
addEventListener is written with a capital L in Listener
'onkeydown' should be 'keydown' when used with the addEventListener function
You closed your brackets in the wrong order (close if, close function, close function call)
You can say something like this
window.onkeydown = function(e){
if(e.keyCode == 40)
changeIdValue("balklongwaard", "60px");
};

Return true if key is down in javascript loop?

I want to add a condition inside a loop that tests if the right arrow is pressed and if it is move a div a bit to the right. However I don't know how to check for they keydown.
I'm using a code to do it but it is really long and I'm sure there is an shorter way to do it.
This is the code:
<div id="char"></div>
<script>
setInterval(function() {
// here it should check if RIGHT (keycode 39) is down and move char 10px to the right if it is;
}, 20);
</script>
How can I check for keydown inside the loop? Btw I'm also using jQuery on the site.
Thanks
Here ya go in raw JS you'd do something like this (press Preview then hold down w):
http://jsbin.com/odalo3/edit
var isPressed = false;
var keydown = function(e){
if(e.keyCode == 87){
isPressed = true;
}
}
var keyup = function(e){
isPressed = false;
}
document.addEventListener("keydown",keydown,false);
document.addEventListener("keyup",keyup,false);
setInterval(function(){
if(isPressed){
document.getElementById('hello').innerHTML = document.getElementById('hello').innerHTML+', pressed';
}
},100)
UPDATE
If you are using jQuery you can change the eventListeners to:
$(window).keydown(function(e){
if(e.keyCode == 87){
isPressed = true;
}
})
.keyup(function(e){
isPressed = false;
})
And delete these lines:
var keydown = function(e){
if(e.keyCode == 87){
isPressed = true;
}
}
var keyup = function(e){
isPressed = false;
}
document.addEventListener("keydown",keydown,false);
document.addEventListener("keyup",keyup,false);
But it's the same thing.
Use jQuery and keydown:
<div id="char"></div>
<script>
$(document).keydown(function(e){
if(e.keyCode == 39){
//do something
$("#char").animate({'left':'+=10'}, 1);
}
})
</script>
Fiddle: http://jsfiddle.net/maniator/zXeXt/
Create a flag var pressed; and set it to true or false in keyPress event; then check it inside the loop

Categories

Resources