Simulate Enter on keyboard JavaScript - javascript

There is an input box for entering number and dumping to the page of a PDF .
user will put the page number in input box and press" enter "on keyboard
i need to Simulate Enter on keyboard in JavaScript.
i tried the following , but it didnt jump to the page i want .
var event = document.createEvent("HTMLEvents");
event.initEvent("change", true, true);
event.eventName = "change";
document.getElementById('input').dispatchEvent(event);
var event = document.createEvent("HTMLEvents");
event.initEvent("keydown", true, true);
event.eventName = "keydown";
document.getElementById('input').dispatchEvent(event);

You can try as per below:
var input = document.getElementById("input");
// Execute a function when the user releases a key on the keyboard
input.addEventListener("keyup", function(event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
// Cancel the default action, if needed
event.preventDefault();
// Trigger the action you want for eg; below code will do the button click action
document.getElementById("myBtn").click();
}
});
Hope it helps your problem.

Related

is there a function to do on a specific keypress instead of click

i was wondering if there is a function i could use instead of using a mouse click as i have set keybinds to whenever i press it it does it on my pc , here is my code i am using for a broswer script on tampermonkey,
}
$('.pagination.prev').on('click' , function(e){
e.preventDefault();
setTimeout(function(){
getPlayerDataFromSite();
}, 500);
});
$('.pagination.next').on('click' , function(e){
e.preventDefault();
setTimeout(function(){
getPlayerDataFromSite();
}, 500);
});
}
instead of using mouse click on the next button and previous button i would like it to use b key as previous and n key as next
thanks in advance for help really appriciate it
Handling a 'keydown' event is rather simple.
You simply listen for the event, then check for the key you are interested in.
For example, this code listens for the keys "b" and "n":
const pre = document.querySelector('pre');
pre.innerText = "";
window.addEventListener('keydown', event => {
// console.log('keydown event:', event);
pre.innerText += `keydown event.key: "${event.key}"\n`;
if (event.key === 'b') {
alert('You pressed "b"');
} else if (event.key === 'n') {
alert('You pressed "n"');
}
});
document.querySelector('button').onclick = () => {pre.innerText = ""};
<h4>Logging 'keydown' Events</h4>
<button>Clear Log</button>
<pre></pre>
Consideratons
As Stephen P mentions, there are some things to be aware of when using 'keydown' events:
holding a key sends repeated keydown events
non-printing keys such as Shift and Control send keydown events
Shift+N produces uppercase N, not lowercase 'n'

Use a preventdefault to get out of the loop after pressing Enter key

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');
}
}
})

Submit button doesn't run function in panel add-on sdk

I am developing an add on using mozilla's add-on sdk. I have a panel attached to a toggle button that contains one input text box and a submit button. When the user presses enter, I am able to get my function to work. However, when I press the submit button nothing happens. Why is this? I have attached my code below:
// When the user hits return, send the "text-entered"
// message to main.js.
// The message payload is the contents of the edit box.
var textArea = document.getElementById("numTimes");
textArea.addEventListener('keyup', function onkeyup(event) {
if (event.keyCode == 13) {
// Remove the newline.
text = textArea.value.replace(/(\r\n|\n|\r)/gm,"");
self.port.emit("text-entered", text);
textArea.value = '';
console.log("Got text from enter");
}
}, false);
// Listen for the "show" event being sent from the
// main add-on code. It means that the panel's about
// to be shown.
//
// Set the focus to the text area so the user can
// just start typing.
self.port.on("show", function onShow() {
textArea.focus();
});
var submit = document.getElementById("search");
submit.addEventListener("click", function submit(){
text = textArea.value.replace(/(\r\n|\n|\r)/gm,"");
self.port.emit("text-entered", text);
textArea.value = '';
console.log("Got text from submit button");
}, false);
The code that's within the textArea section works but the code by the submit section doesn't. Does JavaScript treat these differently?

boolean flag in javascript is not checking properly

i've created a sample application which checks when i press a key or mouse, but the problem is when mouse or when key is pressed it prints the console "Enter is pressed" and "Enter is not pressed some Mouse event is clicked", that boolean checking is not working properly i think so,
can anyone please tell me some solution
$('#adminPanel').bind("searchMaster", function(event, data)
{
var press = true;
$(this).keypress(function(e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code == 13)
{
console.log("Enter is pressed");
press = false;
}
});
if(press)
{
console.log("Enter is not pressed, some Mouse event is clicked");
// some other action to be triggered if key is not pressed
}
});
The problem is, (a) that you register the keypress event inside the click callback and (b) that you set press to false, if is pressed and (c) that you never reset the value of press every time you click with the mouse.
I suggest you split the two callbacks up and move press outside of the callbacks. In the example press => enterPressed. The enterPressed and the callbacks are wrapped in an IIFE to not poluted the global namespace.
(function () {
// by default, "enter" is not pressed
var enterPressed = false;
// Suppose this event is triggered by mouse clicks
$("#adminPanel").bind("searchMaster", function (event, data) {
if (!enterPressed) {
// Handle Mouse Click (no "enter" pressed here)
}
});
// This callback will be triggered if you press a key
// and if you release a key
$("#adminPanel").on("keydown keyup", function (e) {
var code = e.keyCode ? e.keyCode : e.which;
// check if the pressed/released key was "enter"
if (code === 13) {
enterPressed = !enterPressed;
}
});
})();

Why is tab keypress causing focus change also triggering keyup event?

Pressing the tab key which triggers a focus change is also received by the input receiving the focus as a keyup.
a: <input type='text'/><br/>
b: <input type='text' onkeyup='alert("wtf?")'/><br/>
http://jsfiddle.net/59SnP/
As my control also uses tab (not in the example), I would want the focus related keyup event being consumed (but I want to receive other non-focus-change related tab events). I tried to research the rationale behind the current behavior but found nothing. The question: Where is this current behavior specified (event not consumed by focus change), and what would be a cross-browser workaround to force consuming it. Thx.
You can try this. I changed your keyup event in your input :
<input type='text' onkeyup="if(!tabPressed){ alert('This is it !'); }"/>
And I added a little event handler which will raise a flag when the tab button is pressed :
var tabPressed = false;
document.addEventListener('keydown', function (e) {
if(e.keyCode == 9) {
tabPressed = true;
} else {
tabPressed = false;
}
}, false);
Based on Nathan's insight, here is a fully working example:
// First part of Nathan's HACK (set a sentinel when a focus changing tab has happened)
var tabPressed = false;
// remove this listener to break the functionality
$(document).on("keydown", function (e) {
if(e.keyCode == 9) {
tabPressed = true;
} else {
tabPressed = false;
}
});
// The listener on the client input that would kill the keyup tab event upon focus change
$("#magic").on("keyup", function(e) {
if (tabPressed && e.keyCode==9) {
tabPressed = false; // reset the sentinel
e.stopImmediatePropagation()
e.preventDefault()
}
})
And here is the second part, which is a simple skeleton of something meaningful. We disable TAB inside the input, and log it as we do with other keyups:
$("#magic").on("keydown", function(e) {
if (e.keyCode==9) {
e.preventDefault()
e.stopPropagation()
}
})
$("#magic").on("keyup", function(e) {
$(this).val($(this).val() + " " + e.keyCode)
e.stopPropagation()
e.preventDefault()
})
The HTML backing the story is as simple as:
a: <input type='text'/><br/>
b: <input type='text'/><br/>
c: <input type='text' id='magic'/><br/>
If you want to play with it, here it is on jsfiddle
NOTE: This still is not the perfect solution, the sentinel is just reset inside the control, so if a tabpress moving the focus does not activate our input, the sentinel stucks, and the first event will be swallowed.. So here is an example of wrong behaviour:
Click on input A
Press TAB (focus moves to input B, tabPressed becomes true)
Click on input C
Press TAB (it is eaten up as sentinel is true)
Press TAB (now it goes through)
Still it is slightly better to have to press TAB twice as to have something happening automatically, wo user control...

Categories

Resources