Prevent ng-click expression from firing on enter keydown - javascript

I have a simple button like this:
<button type="button" ng-click="$ctrl.method($event)">Test</button>
Here's what the ng-click expression looks like:
vm.method = function($event) {
console.log($event.type, $event.which);
};
When this button has focus (by way of navigating to it via the tab key) and I press enter, I get this output to the console:
click 1
To be more clear that's $event.type == 'click' and $event.which == 1.
I'm not sure why the ng-click directive allows the enter key to fire the assigned expression. Angular is recording enter keydown events as clicks. Is there a way to prevent this and have ng-click only handle click events (and ignore enter)?
This trivial bit of code is just an example, in my app I would like to use both ng-keydown and ng-click on the same component, but this particular issue is preventing me from fully implementing the functionality I want. Ideally, I'd like to have ng-keydown only handle keydown events, and ng-click only handle click events.

Possible but not best way is to check screenX/screenY/pageX/pageY/offsetX... props of $event. In case of "enter" they are equal to zero.

Just prevent default on the key press e.g.
vm.method = function($event) {
if($event.keyCode === 13){ //I think
$event.preventDefault();
}
console.log($event.type, $event.which);
};

If your button is inside a form and it's the only button, the click event will be fired on enter when the form has focus, depending upon the browser. You should be able to check the event object in your handler method and return false if it's the enter key triggering.
https://docs.angularjs.org/guide/expression#-event-

Related

How do I detect if a button was clicked with a keyboard key pressed? (Ctrl-click, Alt-click etc.)

I'm trying to write a UI for an Adobe After Effects script. I want to add a functionality where a user can CTRL click a button instead of just clicking it with no keypresses to get a slightly different behavior.
The problem is, however, I don't to know how to detect if a key was pressed when the button was clicked.
I've managed to detect a keypress with
myPanel.addEventListener("keydown", function (kd) {alert(kd.keyIdentifier); return(kd.keyIdentifier);});
This piece of code adds a listener that alerts me a name of the button when it is being pressed. I also have a button onClick event to control what happens when a button is pressed. However, I can't figure out how to combine those two listeners and get an information about whether a key was pressed during the button click. I tried to place the keydown listener inside the onClick function, but then it doesn't work at all.
I managed to make it work.
The Adobe ScriptUI environment lets you monitor the keyboard status at all times using the Keyboard state object. You can get it from: ScriptUI.environment.keyboardState. It has properties such as altKey, ctrlKey and so on that return a boolean based on whether they key was pressed or not. All you have to do is put the object initiation into the onClick event of the button:
button.onClick = function() {
isCtrlPressed = ScriptUI.environment.keyboardState.ctrlKey;
}
For more information, I refer to p.155 of the Adobe JavaScript Tools Guide
<button onclick="sample(event)">Click Me!</button>
function sample(event){
if (event.ctrlKey){
alert('Button click with ctrlKey pressing.');
}else{
alert('Button click without ctrlKey pressing.');
}
}
Event object has some key press or not. Check that then use it.
Example

Detecting where a submit event came from with jQuery

I need to detect how a user submitted a form to generate some statistics. They can either press enter when typing on the input or they could click the submit button.
I tried binding a click event to the button and a keyup event to the input but what happens is when I press enter the click event is triggered. I read in some other thread that this is part of the new HTML5 spec or something like that.
I then thought of binding a submit event to the form and detecting there what originated that event, but I've had no luck so far. Is that even possible?
EDIT
I guess I managed to fix it. I changed my keyup event to keypress, like suggested by fortegente, and prevented the defaultEvents from firing while at the same time triggering a submit event on the form. That seemed to do the trick.
You can try add custom attribute. Something like this:
$('form').submit(function(){
alert($(this).attr('event'));
});
$("button").on('click', function() {
$("form").prop("event", "click").submit();
});
$("input").on('keypress', function() {
if (e.which == 13) {
$("form").prop("event", "keypress").submit();
}
});

Enter key triggering link

I have a JQuery scroller on a page where each item is a div with an id. each div has a link to the next div in the scroller (all on the same page)
$('a.panel').click(function () {
};
I have a click event to all links with the 'panel' class where I check which links was clicked and then do some ajax processing accordingly:
if($(this).attr('href')=="#item2")
{
//do some processsing
}
and once the processing is done I use the scrollTo JQuery method to scroll to the next div
I need to have it that the user can press the enter key instead of clicking on the link.
Now the problem is:
a. I have several links on the same page that all need to have this behaviour.
b. I need to differentiate which link triggered the click event and do some server-side processing.
Is this possible at all?
I appreciate the quick and helpful responses!!Thanks a million for the help!
Focus + enter will trigger the click event, but only if the anchor has an href attribute (at least in some browsers, like latest Firefox). Works:
$('<a />').attr('href', '#anythingWillDo').on('click', function () {
alert('Has href so can be triggered via keyboard.');
// suppress hash update if desired
return false;
}).text('Works').appendTo('body');
Doesn't work (browser probably thinks there's no action to take):
$('<a />').on('click', function () {
alert('No href so can\'t be triggered via keyboard.');
}).text('Doesn\'t work').appendTo('body');
You can trigger() the click event of whichever element you want when the enter key is pressed. Example:
$(document).keypress(function(e) {
if ((e.keyCode || e.which) == 13) {
// Enter key pressed
$('a').trigger('click');
}
});
$('a').click(function(e) {
e.preventDefault();
// Link clicked
});
Demo: http://jsfiddle.net/eHXwz/1/
You'll just have to figure out which specific element to trigger the click on, but that depends on how/what you are doing. I will say that I don't really recommend this, but I will give you the benefit of the doubt.
A better option, in my opinion, would be to focus() the link that should be clicked instead, and let the user optionally press enter, which will fire the click event anyways.
I would like to focus on the link, but am unfamiliar exactly how to do this, can you explain?
Just use $(element).focus(). But once again, you'll have to be more specific, and have a way to determine which element should receive focus, and when. Of course the user, may take an action that will cause the link to lose focus, like clicking somewhere else. I have no idea what your app does or acts like though, so just do what you think is best, but remember that users already expect a certain kind of behavior from their browsers and will likely not realize they need to press "enter" unless you tell them to.
If you do choose to use the "press enter" method instead of focusing the link, you'll likely want to bind() and unbind() the keypress function too, so it doesn't get called when you don't need it.
http://api.jquery.com/focus/
http://api.jquery.com/bind/
http://api.jquery.com/unbind/
Related:
Submitting a form on 'Enter' with jQuery?
jQuery Event Keypress: Which key was pressed?
Use e.target or this keyword to determine which link triggered the event.
$('a.panel').click(function (e) {
//e.target or this will give you the element which triggered this event.
};
$('a.panel').live('keyup', function (evt) {
var e = evt || event;
var code = e.keyCode || e.which;
if (code === 13) { // 13 is the js key code for Enter
$(e.target).trigger('click');
}
});
This will detect a key up event on any a.panel and if it was the enter key will then trigger the click event for the panel element that was focused.

javascript event handling

want to create a password field where I want to check for capsLock on/off on keystroke. Once a user enters a value in smallcase and try to another field want to validate the password value. Thus want to use onkeypress for every key pressed and then onblur at the end.
But the problem I am facing is every time onkeypress is checked onblur is also executed.
<input type="password" size=50 id='r5PswFld' name="name" value="" onkeypress="checkCapsLock(event)" onblur=chkPsw(this.id) >
can anyone help me how to attain this.
thanks in advance...
better if I am able to do this using only javascript/html/css I me no other technologies like jquery...
This event is getting fired because you in checking the other checkbox input, you are blurring focus away from the current control.
Attach the onblur at the start your checkCapsLock(event) :
document.getElementById("r5PswFld").onblur = function(chkPsw(this.id)'){};
If you find yourself having to perform an action that will focus away, detach it:
document.getElementById("r5PswFld").onblur = function(){};
Next time you fire checkCapsLock it will reacttach if you need to. You could then also remove the onblue attribute completely from your code.
That said, be careful of any onblur validation. If is obtrusive (like an alert) then it could quickly get very frustrating for the user.
EDIT
In repose to the comment below, I thought I'd correct for the problem of other blur bindings. I'll use jQuery for preference.
The correct solution would look something like:
function MyBlurFunc(){
chkPsw(this.id);
}
To bind:
$("#r5PswFld").blur(MyBlurFunc);
To unbind
$("#r5PswFld").unbind('blur', MyBlurFunc);
Unfortunately, onblur will get called whenever focus is left from the field, meaning if you open some sort of message box informing the user of having capslock on, you're removing focus and thus trigger the onblur event.
An alternative might be to activate a flag which you assign to be true prior to opening a message box so that in the case in which you enter chkPsw, you can ignore it.
In other words:
var flgEventsOff = false;
function checkCapsLock(event) {
if (fieldValueIsUpper) {
flgEventsOff = true;
alert('Please turn off capslock!');
flgEventsOff = false;
}
}
function chkPsw(id) {
if(!flgEventsOff) {
// Validate password
}
}
No, the blur event won't be executed the same time a keyPress event is fired. I assume you have an alert() statement within your checkCapsLock() event handler, which causes the loss of focus.
Why would you not just change it to lowecase on the onblur event before it validates?

Capture "done" button click in iPhone's virtual keyboard with JavaScript

I'm wondering if there's a way to capture the iPhone's virtual keyboard's done button event, using JavaScript?
Basically, I just want to be able to call a JS function when the user clicks done.
I was unable to track the 'done' button being clicked. It didn't register any clicks or keypresses. I had to addEventListeners for change, focusout and blur using jquery (because the project already was using jquery).
You need to do some kind of this:
$('someElem').focusout(function(e) {
alert("Done key Pressed!!!!")
});
It worked for me, hope it will help you as well.
After searching and trying this solution
basically is say:
document.addEventListener('focusout', e => {});
tested on IPhone 6s
This question is kinda old, but I've found a hacky way recently to make this working.
The problem with the 'blur', 'focusout' events is that they fire even if user just tapped outside the input/textarea, and did not press the 'Done' button, in my case, UI should behave differently depending on what exactly have happened.
So to implement it, I've done the next thing:
After showing the keyboard (the input received the focus), add click handler on the window via the addEventListener function. When user clicks on the window, remember the timestamp of the click in the variable (let's call it lastClick = Date.now())
In the blur event handler, set a timeout for 10-20 ms to allow other events happening. Then, after the timeout, check if the blur event happened in a time difference lower for example than 50-100 ms than the lastClick (basically Date.now() - lastClick < 50). If yes, then consider it as a 'Done' button click and do corresponding logic. Otherwise, this is a regular 'blur' event.
The key here is that tapping on keyboard controls (including Done button) does not trigger the click event on the window. And the only other way to make keyboard hide is basically tap on other element of the page and make the textarea lose focus. So by checking when the event happened, we can estimate whether that's a done button click or just blur event.
The answer by oron tech using an event listener is the only one that works cross platform.
document.getElementById("myID").addEventListener("focusout", blurFunction);
function blurFunction() { // Do whatever you want, such as run another function
const myValue = document.getElementById("myID").value;
myOtherfunction(myValue);
}
"Change" event works fine
document.querySelector('your-input').addEventListener('change',e=>
console.log('Done button was clicked')
);
attach a blur event to the text box in question. The done fire will fire this event.
The done key is the same as the enter key. So you can listen to a keypress event. I'm writing this using jQuery and i use it in coffee script so I'm trying to convert it back to js in my head. Sorry if there is an error.
$('someElem').bind("keypress", function(e){
// enter key code is 13
if(e.which === 13){
console.log("user pressed done");
}
})

Categories

Resources