I expect the behavior of the program listed below to be like this:
I click on the input.
I press enter.
The line "Press Enter once again" appears.
I go out of input by clicking somewhere on the page.
I press Enter.
Then the line "You have pressed Enter 2 times" appears.
The real behavior of this program:
I click on the input.
I press enter.
The lines "Press Enter once again" and "You have pressed Enter 2 times" appear.
I have 2 questions:
1) What is the reason for that? I have pressed Enter only once.
2) How to make this program behave the way I expect it to behave?
let input = document.createElement("input");
input.value = "Click on this field and press Enter";
input.addEventListener("keydown", function(){
if(event.keyCode === 13){
let div2 = document.createElement("div");
div2.innerHTML = "Press Enter once again";
document.addEventListener("keydown", function(){
if(event.keyCode === 13){
let div3 = document.createElement("div");
div3.innerHTML = "You have pressed Enter 2 times";
document.body.appendChild(div3);
}
});
document.body.appendChild(div2);
}
});
document.body.appendChild(input);
Let's break this down. What is happening is that your if condition is immediately checking if the key was pressed, and it has been so e.keyCode is always 13.
The easiest method to solve this is with the following bit of code:
let input = document.createElement("input");
let isPressed = false;
input.value = "Click on this field and press Enter";
document.addEventListener("keydown", function(e) {
if (event.keyCode === 13 && isPressed) {
let div3 = document.createElement("div");
div3.innerHTML = "You have pressed Enter 2 times";
document.body.appendChild(div3);
}
});
input.addEventListener("keydown", function(e){
event.stopPropagation()
if(event.keyCode === 13){
if ( isPressed ) {
return;
} else {
let div2 = document.createElement("div");
div2.innerHTML = "Press Enter once again";
isPressed = true;
document.body.appendChild(div2);
}
}
});
document.body.appendChild(input);
You can try that out here. You can refractor this to your liking. :)
Keeping your original code in mind, here is the updated version.
To understand how this bit works, it's simple: when there is an event in element a and the wrapper for that element is b, the event travels up through a process known as event bubbling (because bubbles rise up).
Due to that, the second event listener, on the document, gets executed.
To stop that from happening, you can use .stopPropagation() on the event object.
There were a couple of things going on here. You were attaching the listener twice, the second time on the whole document, this event then got triggered instantly when the event bubbled. You didn't need to use two different elements for the message either, if you keep track of if enter was pressed. You should also use textContent over innerHTML for security reasons :)
Here is the code rewritten
let enterHasBeenPressed = false;
let input = document.createElement("input");
input.value = "Click on this field and press Enter";
input.addEventListener("keydown", function(){
if(event.keyCode === 13){
onEnterPressed();
}
});
document.body.appendChild(input);
let text = document.createElement("div");
document.body.appendChild(text);
function onEnterPressed() {
if (!enterHasBeenPressed) {
text.textContent = "Press Enter once again";
enterHasBeenPressed = true;
return;
}
text.textContent = "You have pressed Enter 2 times";
}
https://codepen.io/anon/pen/wbjojR
Related
I need the script for functioning the window.location only after pressing the ENTER key 3 or n times.
This is my current code and i am trying to modify it. Need help, still.
function KeyPress(f) {
var event = window.event? event : f
if (event.keyCode == 13)
window.location = './index.html';
}
document.onkeypress = KeyPress;
Following your instructions, after three press to the key ENTER, it should run the code that will call window.location. In this example, I'm using console.log to prove it is doing what you asking.
Note: When you run it, you need to click with the mouse where it says "Press Enter 3 times.". In this way, the browser will focus on that section. Then, you can press the ENTER key three times.
document.addEventListener("keyup", (e) => enterKeyPressed(e))
let counter = 1;
function enterKeyPressed(event) {
console.log("Key", event.keyCode, " Pressed:", counter);
if (event.keyCode == 13 && counter == 3) {
console.log("Enter key is pressed");
// window.location = "<url you want to go>";
return true;
}
counter++;
return false;
}
Press Enter 3 times.
Check the log.
I am writing a text based game for a college competition and am very new to JS & HTML DOM. I have successfully created an input, and am trying to test it. However, when I type into the input and press enter nothing is logged onto the console...
function new_input(){
let input = document.createElement("INPUT");
input.setAttribute("type", "text");
input.setAttribute("id", "input");
document.body.appendChild(input);
let x = $("input").val();
console.log(x);
You do need to handle the click with the help of a callback.
When wanting to do so use the following code instead of the last two lines
input.onkeypress = (e) => {
if(e.keyCode === 13) {
console.log(input.value);
}
}
I have a input where a user can input text and when the user presses enter on their keyboard, it will click the button 'Go!' which should then make the 'Create Div' button appear. And a div is created with the user's inputted text, when they click the 'Create Div' button. But I want this button to be clicked also when the user presses enter. Thus when the user presses 'Enter' the first time, it will click the 'Go!' button which will make the 'Create Div' button appear and then when the user presses 'Enter' the second time ( or preferably when the 'Create Div' button is shown on the screen) then the actual div will be created with the user's inputted text.
I tried doing this in Javascript, by using an IF statement but right now when I press 'Enter' the first time to trigger the 'Go!' button, it automatically triggers the 'Create Div' button and the div appears right after the first 'Enter' is pressed (uncomment the last bit of my JS code to see what I mean) What should I change to get my desired result?
var button = document.getElementById("button");
var createbutton = document.createElement("button");
var creatediv = document.createElement("div");
button.addEventListener('click', function(){
createbutton.innerHTML = "Create Div";
createbutton.style.display = 'inline-block';
document.getElementById("body").appendChild(createbutton);
});
createbutton.addEventListener('click', function(){
createbutton.style.display = 'none';
var input = document.getElementById("input").value;
creatediv.innerHTML = input;
document.getElementById("body").appendChild(creatediv);
});
document.onkeydown = function(event){
if(event.keyCode == 13){
button.click();
}
}
/*if(createbutton.style.display = 'inline-block'){
document.onkeydown = function(event){
if(event.keyCode == 13){
createbutton.click();
}
}
}*/
<body id="body">
<input type="text" id="input" placeholder="Text goes here">
<button id="button">Go!</button>
</body>
You can give your createbuttonand ID and check if the element is inside the DOM
when enter is pressed:
var button = document.getElementById("button");
var createbutton = document.createElement("button");
var creatediv = document.createElement("div");
button.addEventListener('click', function(){
createbutton.innerHTML = "Create Div";
createbutton.style.display = 'inline-block';
createbutton.id = 'createButton';
document.getElementById("body").appendChild(createbutton);
});
createbutton.addEventListener('click', function(){
createbutton.style.display = 'none';
var input = document.getElementById("input").value;
creatediv.innerHTML = input;
document.getElementById("body").appendChild(creatediv);
});
document.onkeydown = function(event){
if(event.keyCode === 13) {
if(document.getElementById('createButton')) {
createbutton.click();
} else {
button.click();
}
}
}
<body id="body">
<input type="text" id="input" placeholder="Text goes here">
<button id="button">Go!</button>
</body>
I have a special mouse that its control is with the buttons. I mean that when I press left button focus go forward, when I press middle focus go behind and the right one press a click. It is not working good in some objets with the right button because sometines the website doesnt' recognize the click so I was thinking to change the clck with a enter key, I mean when I press the right button I want a key enter push. I don't know If I was very clear. This is the actual code:
$(":focusable").eq(0).focus();
var currentFocus=$(":focusable").eq(0);
$(document).ready(function(){
$("#prueba1").mousedown(function(e){
//1: izquierda, 2: medio/ruleta, 3: derecho
if(e.which == 3) {
//PlaySound3("http://www.soundjay.com/button/beep-06.wav");
//PlaySound3("https://www.soundjay.com/button/button-30.wav");
PlaySound4();
if(currentFocus!=undefined){
currentFocus.focus();
currentFocus.trigger('click');
if(currentFocus.prop('tagName')=='A'){
window.location.href = currentFocus.attr('href');
};
}
return false;
}
if(e.which == 2) {
PlaySound3();
var focusables= $(":focusable");
var current= focusables.index(currentFocus);
var previous = focusables.eq(current-1).length ? focusables.eq(current-1) : focusables.eq(0);
currentFocus=previous;
previous.focus();
return false;
}
if(e.which == 1) {
parar();
PlaySound();
//PlaySound3("http://www.soundjay.com/button/beep-07.wav");
var focusables= $(":focusable");
var current= focusables.index(currentFocus);
var next = focusables.eq(current+1).length ? focusables.eq(current+1) : focusables.eq(0);
currentFocus=next;
next.focus();
return false;
}
});
});
Thank u so much!
Trigger enter key on right click like this.
var e = $.Event( "keypress", { which: 13 } );
$('#yourInput').trigger(e);
This is a complete revision of my initial question, all unnecessary resources and references were deleted
I am tying the same event listener to 2 different elements: a button and Enter key, and it looks like the following:
var funcelement = function(){
//function code
};
$('#buttonID').click(funcelement);
$('#inputID').keyup(function () {
if (event.which == 13) {
$('#buttonID').trigger('click');
}
})
What I am trying to do is to prevent propagation of the enter key press if focus is on the submit button(#buttonID) by using preventDefault().
So I tried various combinations to make it work. The following is the latest result on my attempts
$('#inputID').keyup(function () {
var hasfocus = $('#buttonID').is(':focus') || false;
if (event.which == 13) {
if (!hasfocus) {
event.preventDefault();
$('#buttonID').trigger('click');
//hasfocus = true;
}
else {
//event.preventDefault();
//$('#buttonID').trigger('click');
}
}
})
After I enter a text into an input box and press Enter key, a confirmation window with yes/cancel buttons pops up with focus on yes button. Once I press Enter again, another window confirming that changes were made pops up with Ok button focused on it. Once I press Enter again, everything I need is being made.
However, there is one problem: after the last step is done, I am going back to the if (!hasfocus) line.
How do I prevent that from happening? Once the stuff I need is done - I don't want to go into that line again.
You can pass a parameter to into the function and stop the propagation there like so:
var funcelement = function(event, wasTriggeredByEnterKey){
if (wasTriggeredByEnterKey && $('#buttonID').is(':focus')) {
event.stopPropagation;
}
//function code
};
$('#buttonID').click(funcelement);
$('#inputID').keyup(function () {
if (event.which == 13) {
$('#buttonID').trigger('click', [true]);
}
}
)
UPDATE
In order to answer your revised issue, you should use the "keydown" event rather than "keyup" when working with alerts. This is because alerts close with the "keydown" event but then you are still triggering the "keyup" event when you release the enter key. Simply change the one word like this:
$('#inputID').keydown(function () {
var hasfocus = $('#buttonID').is(':focus') || false;
if (event.which == 13) {
if (!hasfocus) {
event.preventDefault();
$('#buttonID').trigger('click');
//hasfocus = true;
}
else {
//event.preventDefault();
//$('#buttonID').trigger('click');
}
}
})