Way to associate a keyboard shortcut to mouse event - javascript

I'm wiriting an Ajax web application with jQuery.
I need to link almost every click event to a keyboard shortcut.
My idea is to use a function like this to bind the events:
$.fn.myclick = function(element, key, customFunction) {
$("body").on("click keypress", element, function (event) {
if (event.keyCode === key || event.keyCode === undefined) {
customFunction();
}
});
};
I'm quite sure this is not a good way and you do know a best way to perform this task.
I think the problem with my method would be that the event could be fired even when I change page and I press the key. I should add some kind of unbind or a way to fire the event only when the user is on the correct page.
The pages are just a list of <section> hidden with display: none; except for the one active.
Any suggestion?

Take a look at js libs for handling keyboard events. Choose any you (or the community) like: http://microjs.com/#keyboard

Related

adding the keyboard events using the addEcent Listener

i am using el-pagination by element UI and i want to the #keyup.enter & #keyup#space events to it, right now we do not have any kind of key event to it
i am trying to create an addeventlistenber but i am not sure how it should work, i added some code but that does not seems to be working, if anyone has an idea how to fix it, please share
here is my try
document.querySelector('.el-pagination').addEventListener('#key.enter',function(e) {
what should i write here i am have no clue,
});
should i write it on the el-input element inside the el-pagination or where exactly
There is nothing like #key.enter in javascript. You can use either keyup or keydown event listener for .el-pagination.
After that you have to check for event key, whether it is "Enter", "Space" etc. You can this by .key method.
document.querySelector('.el-pagination').addEventListener('keyup', function(e) {
if(e.key === "Enter" || e.key === "Space") {
//Your code here
}
});

Key event binding at table level

I have 2 tables on 1 page. I would like the user to be able to click the table and then use the arrow keys to navigate to previous and next. The only way I have been able to get the keyup events to fire in all browsers is by attaching them directly to the 'document'. I have wired up an event to add a 'grid-focused' class to the grid that is in focus and I tried using that as the selector on my events but I cannot get any event action then.
Event Binding
function attachInitEvents() {
if ($self.config.pageHotKeysEnabled) {
var keyNav = function(e) {
if (e.keyCode == 37 && paging.hasPrevious) { // left
$self._log.info('Left arrow key pressed.');
fetchData('prev');
}
if (e.keyCode == 39 && paging.hasNext) { //right
$self._log.info('Right arrow key pressed.');
fetchData('next');
}
}
var $doc = $(document);
// hot key support
$doc.off('keyup');
$doc.on('keyup', keyNav);
}
}
I am having another issue, where I am doing $doc.off('keyup'). I think this is part of the problem as it is unbinding all keyup events, what I really want is for it to just unbind the event I am trying to attach if it exists. In jQuery docs it technically says I should be using $doc.off('keyup', keyNav); to unbind it, but it does not unbind the event and I get multiples of it.
So core questions are,
Can I trigger a KeyUp event without binding to the document and can I do it from the table level?
How can I properly make sure I am not rebinding over and over again? Now, if this page has 2 tables, I guess I would expect there
to be 2 events one for each table and then the .grid-focused class
would be what allows the event to trigger or not?
Here is a Fiddle: http://jsfiddle.net/93fp293w/
Basically, I have no input boxes it is just spans, I am basically making it easier for them to page through all the data by just using the arrow keys. I believe the fiddler is pretty accurate to the situation. I feel what I am asking is not possible since I wont have an actual control in focus and if that is the case I can accept that but I guess I am hoping there is a work around.
The problem with attaching keyup is that, the parent div has to be mutable(contenteditable). else you have to attach to the document.
I have updated fiddle, might be a hack let me know if this works for you ?
http://jsfiddle.net/puneethp/qfpyeydg/3/
$(document).on("keyup", function (e) {
e.target = $(".focus")[0];
..
}
if you have only one column focused at a time, my previous fiddle will still work.

toggle buttons using tab

It is simple. I have two buttons in a web page. They are sitting closely.
Currently I use mouse to click one of them then doing something.
Can we just use keyboard such as TAB?
Thanks.
Using tab to press buttons will completely break accessiblity on you websites and will effectively drive away any keyboard users from your website, it's an awful practice.
In any case, you might want to capture events for '*' using jquery:
$('*').keydown(function(event) {
if (event.keyCode == 9)
//stuff
})
Though I'd strongly recomend agaist doing this; never override what keys such as tab do, you'll create huge accessiblity issues.
[EDIT]:
Adding the event to document might be more efficient:
If key presses anywhere need to be caught (for example, to implement
global shortcut keys on a page), it is useful to attach this behavior
to the document object. Because of event bubbling, all key presses
will make their way up the DOM to the document object unless
explicitly stopped.
Source
jQuery would be perfect for this just bind the key to that button. something like this.
$('your selector here').keyup(function(e){
if(e.which == '9'){
//do your stuff here
}
});
I think 9 is the correct charcode for tab but you might need to check that. and make sure you do this inside of $(document).ready();
Yes, hit Tab until the button has a dotted border to indicate focus, then you can hit Enter or Space to click the button.
E.g. Button 2 has the focus here and pressing Space or Enter would "click" it:

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.

How to change all onClick events to TouchStart on iOS?

OnClick event has a timeout ~400ms before executing on iOS-browser (demo). And I want to change it to TouchStart event for all DOM-elements who have onClick. How can i make it?
I use jQuery and i tried check all elements for click function:
$('*').each(function() {
if($(this).click != null) {
// BUT all elements in DOM has click
}
})
I don't have an exact answer, but I think you should be able to make this do what you want.
For every element on your page that has an OnClick, add a class - say TouchTarget. Then use this in your startup function.
$('.TouchTarget').bind('touchstart', function (e) {
e.preventDefault();
touchStart(e, this);
});
Create a handler function that looks like this:
function touchStart(pEvent, pElement) {
//Do something with the touch.
}
If you only want to register if touch is available, then you can protect the bind call with
if (Modernizr.touch) {
}
I believe the reason for the delay in OnClick is because Safari is waiting to see if the touch is really a click or a drag, or some other gesture. This will recognize a simple touch quickly. I normally bind both touchstart and touchend when I need quick touches so that touchstart provides visual feedback and then touchend does something with the "click". This method does not have a delay built in.
Use a product like http://www.jqtouch.com/ or the code snipped provided here: http://cubiq.org/remove-onclick-delay-on-webkit-for-iphone.

Categories

Resources