Keyup event in focused input when clicked link - javascript

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.

Related

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

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

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

Jquery - Differentiate between 'click' and 'focus' on same input when using both

I'm trying to trigger an event on an input if the input is clicked or if the input comes in to focus.
The issue i'm having is preventing the event from firing twice on the click as, obviously, clicking on the input also puts it in focus. I've put a very loose version of this on jfiddle to show you what I mean, code as below:
HTML:
<body>
<input type="textbox" name="tb1" class="input1"></input>
<label> box 1 </label>
<input type="textbox" name="tb2" class="input2"></input>
<label> box 2 </label>
</body>
JQuery
$(function () {
$('.input2').click(function() {
alert("click");
});
$('.input2').focus(function() {
alert("focus");
});
});
JSFiddle: http://jsfiddle.net/XALSn/2/
You'll see that when you tab to input2 you get one alert, but if you click you get two. Ideally for my scenario, it needs to be one alert and ignore the other. it also doesn't seem to actually focus.
Thanks in advance for any advice.
How about setting a flag on focus so we can fire on focus and ignore clicks but then listen for clicks on the focussed element too? Make sense? Take a look at the demo jsFiddle - If you focus or click on the unfocussed .index2 it triggers the focus event and ignores the click. Whilst in focus, clicking on it will trigger the click.
I have no idea why you would want this (I cant imagine anyone wanting to click on a focussed element for any reason (because the carat is already active in the field) but here you go:
$(function () {
$('.input2').on("click focus blur", function(e) {
e.stopPropagation();
if(e.type=="click"){
if($(this).data("justfocussed")){
$(this).data("justfocussed",false);
} else {
//I have been clicked on whilst in focus
console.log("click");
}
} else if(e.type=="focus"){
//I have been focussed on (either by clicking on whilst blurred or by tabbing to)
console.log("focus");
$(this).data("justfocussed",true);
} else {
//I no longer have focus
console.log("blur");
$(this).data("justfocussed",false);
}
});
});
http://jsfiddle.net/XALSn/12/
This probably won't be the best answer, but this is a way of doing it. I would suggest adding tab indexes to your inputs and firing the focus event when you blur from another input.
I've added that to this fiddle:
http://jsfiddle.net/XALSn/9/
$(function () {
$('.input2').click(function(e) {
alert("click");
e.preventDefault();
});
});
$('input').blur(function(){
$('input').focus(function() {
alert("focus");
});
});
You can use one thing I am using very often in JS
var doSomething = true;
$(function () {
$('.input2').click(function(e) {
if (doSomething) {
// do something :)
}
doSomething = false;
});
$('.input2').focus(function() {
if (doSomething) {
// do something :)
}
doSomething = false;
});
});
But You have to change value of doSomething on mouseout or foucs over etc. :)
$(function () {
var hasFocus = false;
$("body")
.off()
.on({
click : function()
{
if(!hasFocus)
{
hasFocus = true;
alert("click");
}
},
focus : function()
{
if(!hasFocus)
{
hasFocus = true;
alert("focus");
}
}
},".input2");
});
try setting a flag hasFocus and act accordingly
http://jsfiddle.net/AEVTQ/2/
just add e.preventDefault() on the click event
$(function () {
$('.input2').click(function(e) {
console.log("click");
e.preventDefault();
e.stopPropagation();
});
$('.input2').focus(function() {
console.log("focus");
});
});
If I understand your question right, the e.prevnetDefault() will prevent the browser from automatically focusing on click. Then you can do something different with the click than would with the focus

jQuery event binding with accessibility in mind - click and keypress

Just a quick question, I seem to do this a lot:
$saveBtn.bind("click keypress", function(e)
{
if (e.type != "keypress" || e.keyCode == 13)
{
// Do something...
return false;
}
});
Is there a quicker way to bind an 'action' listener to a button? I want to always ensure my buttons with event listeners fire on both clicks and the enter key...this seems like it'd be a fairly common thing to want to do but found nothing on google. Any thoughts?
Thanks.
The click event doesn't actually handle the keypress in every case, it's the button that is making the click event work. When you use a div with a tabindex attribute to make it keyboard accessible, the click handler will not trigger when you press enter.
HTML
<div id="click-only" tabindex="0">Submit click only</div>
<div id="click-and-press" tabindex="0">Submit click and press</div>​
jQuery
$("#click-only").click(function (e) {
addToBody(); // Only works on click
});
$("#click-and-press").bind("click keypress", handleClickAndPress(function (e) {
addToBody(); // Works on click and keypress
}));
function addToBody() {
$("body").append($("<p/>").text("Submitted"));
}
function handleClickAndPress(myfunc) {
return function (e) {
if (e.type != "keypress" || e.keyCode == 13) {
myfunc(e);
}
};
}
So to answer the question, I don't think there is a better way (that works in every case) other than yoda2k's solution.
By binding it with click will do the job, no need for keep press. Example
You could create a second function which handles the additional logic and pass your function as a parameter:
function handleClickAndPress(myfunc)
{
return function (e) {
if (e.type != "keypress" || e.keyCode == 13) {
myfunc(e);
}
};
}
$saveBtn.bind("click keypress", handleClickAndPress(function (e) {
// do your stuff here
}));
If it's part of a form you could just listen for the "submit" event?

Categories

Resources