After Press e.keycode 13(enter key) console value printed multiple time - javascript

I have written one Small script. By clicking the tab, it will show the console value "hotspot div is focused" then if I hit enter in the same div it will show the console value "Enter key is pressed". First time it's working totally fine. But the problem is if I click the tab second time and hit enter, in the console "Enter key is pressed" this value showing twice. And that value increased every time. How can I prevent it and make it triggered once each time without page load?
Code is attached below
$( ".main-nav__menu-hotspot" ).focus(function() {
console.log("hotspot div is focused");
$(".main-nav__menu-hotspot").keypress(function (e) {
if (e.keyCode == 13) {
console.log("Enter key is pressed");
$('.main-nav-overlay').toggleClass('main-nav-overlay--menu-open');
$('.main-nav--gct').toggleClass('main-nav--menu-open');
}
e.preventDefault();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main-nav__menu-hotspot" tabindex="0">menu</div>
<div class="main-nav-overlay">
overlay
</div>
<div class = "main-nav--gct">
nav
</div>

What you're doing is creating a new keypress event listener, every time the $( ".main-nav__menu-hotspot" ).focus() event listener is triggered.
e.g. if you hover over the menu 4 times (or whatever triggers the focus event), it'll create 4 keypress event listeners. So when you do the keypress, it'll execute 4 times.
Move the keypress event listener creation out of the other one:
$( ".main-nav__menu-hotspot" ).focus(function() {
console.log("hotspot div is focused");
});
$(".main-nav__menu-hotspot").keypress(function (e) {
if (e.keyCode == 13) {
console.log("Enter key is pressed");
$('.main-nav-overlay').toggleClass('main-nav-overlay--menu-open');
$('.main-nav--gct').toggleClass('main-nav--menu-open');
}
e.preventDefault();
});

Related

Detect input button down state

How can I detect if the button below is currently pressed down (being held down)?
<input type="button" value="Hold it down" id="aButton">
To clarify, I don't mean to detect if the button is clicked, but being held down in the active state.
I tried to use the mousedown event but it doesn't work if the user operates the button with the keyboard, tabbing to the button and holding the space bar down.
It work fine with jquery mousedown (onmousedown in native js ) mouseup (onmouseup in native js ) events , bellow the working sample :
$(document).ready(function(){
$("#btn").on("mousedown",function(){
console.log("btn click down using mouse");
})
var firstKeydown = true;
$("#btn").on("keydown",function(e){
if(e.which == 32){ // check if clicked button is sapcebar "code =32"
if(firstKeydown) { // to prevent multiple firing
console.log("btn click down using keyboard");
firstKeydown = false;
}
}
})
$("#btn").on("mouseup",function(){
console.log("btn click up using mouse");
})
$("#btn").on("keyup",function(e){
if(e.which == 32) { // check if clicked button is sapcebar "code =32"
console.log("btn click up using keyboard");
firstKeydown =true;
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Button</button>

Button with focus - run function on 'Enter'

I have my code below. It's doing what I want. What I want to also do is run this function when a user use their keyboard to tab to the .add-row button and then presses enter. How do I make that run?
$('body').on('click', '.add-row', function(e) {
$( this ).html('Hide').removeClass('add-row').addClass('hide-row');
$( this ).parent().parent().next().show();
});
My understanding is you want the button to have focus and the user to press enter to fire the event, yeah? If so, then using the :focus pseudo class selector on the .add-row should work with the keypress event
$("body").on("keypress", ".add-row:focus", function(e) {
var ENTER_KEY_CODE = 13;
if (e.keyCode === ENTER_KEY_CODE)
{
alert("Enter key pressed");
// perform hide row and other operations here
}
});

jquery - add event handler on event that takes another event as argument

I am trying to call a function scheduleAdd when the enter button is hit, but I only want it to work if an input with the id 'addSchedule' is in focus. Here's what I have:
$('#addSchedule').focus(function(e) {
var evt = e || window.event;
if(evt.keyCode == 13) {scheduleAdd};
});
I know the code inside the .focus works, because I tried it on its own and it triggers the function scheduleAdd when the enter key is hit. How can I make this conditional on 'addSchedule' being in focus?
Also, more generally, I was wondering if there's a standard way to ascribe event handlers conditional on a second event, such as nesting .on() or something.
Thanks.
Demo on fiddle
HTML:
<form>
<input id="addSchedule" type="text" />
</form>
Javascript:
$('#addSchedule').keydown(function (event) {
if (event.which == 13) {
event.preventDefault(); // This will prevent the page refresh.
scheduleAdd();
}
function scheduleAdd() {
alert("Add the schedule");
}
});
Simply the keydown event, and decide to do something or nothing based on whether the current element has the specified id:
$(document).on("keydown", function() {
if (!$("#addSchedule").is(":focus")) return;
// do stuff
});
Alternatively you can also check for the identity of the focused element with document.activeElement.id === "addSchedule" if you don't mind that's not enough jQuery. ;-)

Keyup event in focused input when clicked link

I have a button and when it have clicked I show some input field.
The input field tracks keyup events itself.
When I click the button using my keyboard (focus it then hit return) the input field receives an unexpected keyup event.
Demo: http://jsfiddle.net/LpXGM/3/ (just hit return and look at the messages on the page)
But if I add a timeout everything works as expected. Demo: http://jsfiddle.net/8BRmK/1/ (no keyup event when hitting return on the button)
Why does this strange thing happen? And how can I fix it?
The code with the handlers:
$button.on("click", function(){
showModal();
});
$emailField.on("keyup", function(event) {
// process the event
});
var showModal = function() {
$modal.show();
$emailField.focus();
}
Possible solution without timeOut: http://jsfiddle.net/agudulin/3axBA/
$button.on("keypress", function(event){
if (event.keyCode == 13) {
return false;
}
});
$button.on("keyup", function(event){
if (event.keyCode == 13) {
showModal();
$status.append($("<span>enter has been pressed</span></br>"));
}
});
Try $button.on("keyup mouseup", function(){
or $emailField.on("keypress", function(event) {
try
$(document).ready(function(){
$(document).on("click",".btn",function(e){
$status.append($("<span>btn click</span></br>"));
});
$(document).on("keyup",".email",function(e){
$status.append($("<span>keyup " + event.keyCode + "</span></br>"));
});
});
yes its happens because one you click the keyboard than the button click event fire first and than as per your logic your input field take focus and your keyup event is fire. but when you give Timeout so click event is fire first but because of timeout your logic is delayed and than your your keyup event done our work so the focus in not in your input that why it not enter any word in your input.

jQueryUI Button on a form to be default button on hitting Enter key

I have a jQueryUI button on a form (not a modal dialog). I want it to be fired when the user hits the Enter key. How can I do this? Here is my code:
HTML:
Login
JS:
$(document).ready(function ()
{
$("#loginButtonInner").button(getButtonOptions("ui-icon-unlocked", true));
$("#loginButtonInner").button("option", "disabled", true);
$("#loginButtonInner").unbind("click");
}
....
if (userNameValid && passwordValid)
{
$("#loginButtonInner").button("option", "disabled", false);
$("#loginButtonInner").unbind("click").bind("click", function () { authenticateUser(); return false; });
}
else
{
$("#loginButtonInner").button("option", "disabled", true);
$("#loginButtonInner").unbind("click");
}
Currently, I have to tab to reach the button via the keyboard or click via the mouse.
I searched for solutions online, but they all point to a modal dialog form button .
Thanks!
Add a key listener to your form elements and watch for the Enter key, then trigger the click from your button:
$(yourform).find('*').keypress(function(e) {
if ( e.which == 13 ) { // 13 is the code for Enter key
e.preventDefault();
$(yourbutton).click();
}
});
You should be able to use the jQuery.focus() function.
For example:
$("#loginButtonInner").focus();
Will cause the element with ID of loginButtonInner to receive focus. So when you press enter, if that element is a button it will be pressed.
Update: I tried it with a jQueryUI button and it works fine.

Categories

Resources