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.
Related
I'm having some buttons that can be clicked either by mouse or key presses. Then I have a function called by space-key.
The problem is that when one of the buttons has been clicked with mouse, it seems the button gets selected (focussed) and when the space-key (and enter-key) gets pressed afterwards, the browser calls the selected (focussed) button instead of the intended function for the space key.
I've found a solution long time ago so I know there is a solution but can't remember.
Edit: This is not inside a form.
If you don't need the spacebar for your form, you can do an event.preventDefaut() on keypress for the spacebar.
$(yourbuttonelements).keydown(function(e) {
var kc = e.keyCode;
if (kc === 32){
e.preventDefault();
}
});
If you wish to bypass the default event on a keypress, you need to first delegate a 'keypress' or related event and then check for event.which to find the corresponding key pressed and if it matches with what you want to prevent, you can either do return false; or do event.preventDefault();
Example :
$('button').on('keypress',function(e)
{
if(e.which == 32) // 32 -> represents the keycode of space bar
e.preventDefault();
});
preventDefault() didn't work though I found a solution.
As mentioned, the problem was the button got focussed when clicked, so I used blur() for the button.
document.getElementById(id).blur();
I am trying to intercept "Hide keyboard button" specific for Ipad in Javascript. I searched everywhere but could not find correct keycode for that.
I pressed any keys and I get a keycode map (for characters, but also for enter, space and delete..).
This is an example of what I want to accomplish
$( "#mydiv" ).on( "keydown", function( event ) {
if (event.which == xx){
//do something
}
}
where xx is my keycode on 'hide keyboard button'. No method is called to the delegate when the button is pressed nor a KeyCode.
I took a look at detect iPad keyboard Hiding button, but I get a solution on a different level (with Xcode), but I need a solution with Javascript.
Hope someone could help.
I found a workaroud for iPad IOS7. I will test on IOS8 to make sure it works. So basically I create a listener on every FOCUSOUT event (for all my texts) and I call my function.
It fires when you have your keyboard open and when you close your "keyboard". It doesn't fire when you select another text field or button, because it targets on null. If you use in combination with keydown, you can save multiple value and call your submit function only when you release your keyboard.
It works for my specific project.
document.addEventListener('focusout', function(e) {
if (e.relatedTarget === null) {
alert("close keyboard without click on something else");
callYourFunction();
}
});
p.s
I'm pretty new here in SO, so I don't know if I can reply myself or I should edit my question or make a comment.
I'm developing one of those warning windows that tells the user that they may have unsaved data, but I only need it to warn them if they're leaving the page. Currently it does so on refreshes, postbacks, etc. I was wondering if there was any way to tell how the page was unloaded or otherwise get more details about what the user is doing to unload the page. (jquery solutions welcome).
Code for reference:
window.onbeforeunload = function () {
if (formIsDirty) {
formIsDirty = false;
return "Are you sure you want to navigate away from this page?";
}
}
on beforeunload event we can do below things:
We can pass event as a parameter to the function as in above answer.
Now we can use this event for available information attached to this
event.
And we can access Document level variables.
For example document.activeElement will give you the last element you clicked that caused the page unload.
Hope this helps!!
I think that the active element is not a valid solution.
I can't comment the "open and free" solution, I dont have reputation.
document.getActiveElement gets the currently focused element in the document. If a link have the focus and I press F5 or I close the tab the active element is the link.
Short answer: There's no easy way to find out what is causing onbeforeunload to fire.
Long answer: Inside your window.onbeforeunload handler you can access the window.event object, which may have some useful properties to determine how the window is closing.
For example, if window.event.srcElement is an anchor tag, then you know that the onbeforeunload event is firing by an anchor tag being clicked.
Refer to the event and onbeforeunload pages on MSDN for more properties.
Edit: some more info I have stumbled across -
If you want to ignore ASP controls that cause post-back, you can interrogate the '__EVENTTARGET' hidden input. If this input has a non-empty string value, then the page is being posted back by an ASP control.
You could also check the keyCode property (if F5 has been pressed, causing a refresh) or the mouse position to see if the X (close) button has been clicked.
I was running into a simular issue when a user was hitting enter from an input field on a form. The form was being submitted thus firing off the onbeforeunload event. I tried setting a flag to avoid showing the message on the keydown event on the input, filtering on the enterkey code. This wasn't getting triggered until after the onbeforeunload event was firing and therefore the flag wasn't getting set.
I then looked into the _EVENTTARGET as jbabey suggested. If the form was being submitted there would be a value in that field, if it was being refreshed there wouldn't.
Therefore, doing a simple check to see if there was value in the _EVENTARGET field in the onbeforeunload event could determine if the input from the form was causing the postback.
Here is my code.
window.onbeforeunload = function (e) {
if ($('[id$=__EVENTTARGET]').val().indexOf('btnValidateMaterials') != -1) {
confirmExit = false;
}
if (DateOrQtyHasChanged() && confirmExit) {
if (/Firefox[\/\s](\d+)/.test(navigator.userAgent) && new Number(RegExp.$1) >= 4) {
var message = $('[id$=hfLeaveMessageFF]').val();
if (confirm(message)) {
history.go();
}
else {
window.setTimeout(function () {
window.stop();
}, 1);
}
}
else {
var message = $('[id$=hfLeaveMessage]').val();
return message;
}
}
}
I have a usability concern on a web site of mine. I have a set of tabs, each containing a form. When you click on the tab link, it gives focus to the first textbox in the tab content body. Mouse-oriented people love this "feature". The problem is when keyboard-oriented users use the TAB key on their keyboard to go through the tabs. They hit enter on the tab they want to look at, the click event fires and the tab shows up, but focus is given to the textbox, adjusting their tab order completely. So when they hit tab again, they want to go to the next tab on the screen, but since focus was moved inside the form, they can't easily get to the next tab using the keyboard.
So, inside the click event I need to determine if they actually clicked on it with a mouse button. Is this possible? My first attempt was this:
$("#tabs li a").click(function(e) {
var tab = $(this.href);
if(e.keyCode != 13)
$("input:first", tab).focus();
});
But keyCode is always 0. The which property is also always 0. Please help!
Here's the solution I came up with, it's surprisingly simple. I trapped keydown on the tab links, and triggered the click event when keyCode was 13. Luckily, the trigger function allows us to pass extra parameters to the event handler...
$("#tabs li a").keydown(function(e) {
if(e.keyCode == 13) {
$(this).trigger("click", true);
e.preventDefault();
}
});
So I just had to change my click handler to receive the new parameter and use it...
$("#tabs li a").click(function(e, enterKeyPressed) {
if(enterKeyPressed)
alert("Enter key");
else
alert("Clicked");
});
I put up a demo on jsFiddle as well. Thanks to everyone who read the question.
An even simpler solution that worked for me was to just check whether there were any mouse coordinates passed with the event.
document.addEventListener('click', function(e) {
//if the event object is passed with mouse coordinates,
if(e.screenX && e.screenY){
//The mouse was clicked
}else{//The enter key was pressed}
});
Would a global "focus" variable work, which disable focus on mouse setting after tab usage on a given tab until a mouse is moved to a new block.
This would not be the feature your requesting, but I believe it might give you what your looking for.
eg. mouse hoovers option 5, you hit tab, now you store the 5 in the variable, disallowing focus to 5 until something else been focused on, but as soon something else is focused, global is turned back to -1.
Not cleanest workaround I admit that freely.
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");
}
})