toggle buttons using tab - javascript

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:

Related

jQuery click event - How to tell if mouse was clicked or enter key was pressed?

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.

Spacebar key press on anchor html element doesn't trigger click event. How to let this happen?

<a tabindex="7" style="cursor: pointer;" class="button" id="saveTocAddNew" onClick="saveTdsAddNew();"/><span>Save & Add Another</span></a>
I have the above anchor element in my page. This one is styled to look like a button and so will be treated as a button. The problem is as follows. The user doesn't want to use mouse to click on it or reach it, but he will use the tabbing to highlight this anchor element and then will use "spacebar" or "return" keys to click on it. If the user hits on spacebar or return key I should be able to call a JavaScript function. I tried the onkeypress event and that doesn't help. Any idea?
First: there's a problem with your HTML. You're using the short syntax for the A -- meaning that the text isn't actually part of the A content. Many browsers don't like the short syntax for A tags anyway -- not your fault, but it's our job to be more tolerant than browsers are.
Here's the corrected version:
<a tabindex="7" style="cursor: pointer;" class="button" id="saveTocAddNew" onClick="saveTdsAddNew();"><span>Save & Add Another</span></a>
Depending on the browser and DOCTYPE, it is significant whether the event name is all lowercase or not. Just something to look for.
Finally, by default your onclick event will only fire for clicks and Enter -- not for spacebar. Many browsers treat the spacebar as a pagedown thing. If you are sure you want to capture spacebar events on this A and treat them like Enter, you'll need to define a keypress event that looks for spacebars. Like so:
function addNewKeys(event) {
if(!event) var event = window.event; // cross-browser shenanigans
if(event.keyCode === 32) { // this is the spacebar
saveTdsAddNew(event);
}
return true; // treat all other keys normally;
}
(Remember to bind this new function to the onkeypress of that A.)
Note that I'm passing the event to the saveTdsAddNew function. That's because I think event handlers normally receive the event object as their argument, so this preserves the existing pattern. From the event, you can retrieve the element that was clicked/keyed-on, etc.
I haven't personally tried to do this, but I wager it's a little more involved then just setting up a keypress event on the hyperlink.
I imagine what you need to do is handle the keypress at document level, within that check to see if your hyperlink is focused, then execute the code you wish.
It's also worth seperating the on-click event from the HTML.

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

Initiating key strokes in JavaScript

Let's say I have a web page with a header menu, when I click the header menu, it calls a servlet that creates the sidebar. Is it possible that without using the document.getElementById? And just simulate keystrokes tab and enter via JavaScript so I don't have to click the menu to view the sidebar?
Could you describe what you want to achieve a bit more?
What I understood is that you want to be able to show ( and may be also hide) the sidebar with the tab button.
You could use the .keypress() function in jQuery - http://api.jquery.com/keypress/
Also check out this tutorial on Nettuts, I think it may be useful for you -
http://net.tutsplus.com/tutorials/javascript-ajax/how-to-create-a-keypress-navigation-using-jquery/
You can use the attribute tabindex on the elements that makes your menu.
eg: <ul tabindex="1">... and set the focus on the first one when opening the page.
They will act as form field when you press tab.
Then for the enter place a single onkeyup listener on a parent node common to all menus items:
menuParent.onkeyup = function(ev){
var selectedMenu = ev.target || ev.srcElement,
keycode = ev.keyCode;
if(keycode === 13){
//the user pressed enter
}
...
}
You can do what you want using JavaScript, but there's a much easier way to do it than by simulating keystrokes.
I am assuming that what happens when you click the link is that a JavaScript function is called, which causes the submenu to appear. All you need to do is to find out what that function call is (let's say it's called "callTheFunction"), and then call it onload, like this:
<script type="text/javascript">
window.onload=callTheFunction;
</script>
Hopefully that will give you the idea. If you need any more help, please provide a URL or code sample.

middle click (new tabs) and javascript links

I am in charge of a website at work and recently I have added ajaxy requests to make it faster and more responsive. But it has raised an issue.
On my pages, there is an index table on the left, like a menu. Once you have clicked on it, it makes a request that fills the rest of the page. At anytime you can click on another item of the index to load a different page.
Before adding javascript, it was possible to middle click (open new tabs) for each item of the index, which allowed to have other pages loading while I was dealing with one of them.
But since I have changed all the links to be ajax requests, they now execute some javascript instead of being real links. So they are only opening empty tabs when I middle click on them.
Is there a way to combine both functionalities: links firing javascript when left clicked or new tabs when middle clicked?
Does it have to be some ugly javascript that catches every clicks and deal with them accordingly?
Thanks.
Yes. Instead of:
...
Do this:
...
And then in your JS, hook the link via it's ID to do the AJAX call. Remember that you need to stop the click event from bubbling up. Most frameworks have an event killer built in that you can call (just look at its Event class).
Here's the event handling and event-killer in jquery:
$("#thisLink").click(function(ev, ob) {
alert("thisLink was clicked");
ev.stopPropagation();
});
Of course you can be a lot more clever, while juggling things like this but I think it's important to stress that this method is so much cleaner than using onclick attributes.
Keep your JS in the JS!
Yes, You need to lookup progressive enhancement and unobtrusive Javascript, and code your site to work with out Javascript enabled first and then add the Javascripts functions after you have the basic site working.
I liked Oli's approach, but it didn't discern from left and middle clicks. checking the "which" field on the eventArgs will let you know.
$(".detailLink").click(function (ev, ob) {
//ev.which == 1 == left
//ev.which == 2 == middle
if (ev.which == 1) {
//do ajaxy stuff
return false; //tells browser to stop processing the event
}
//else just let it go on its merry way and open the new tab.
});
It would require some testing, but I believe that most browsers do not execute the click handler when you click them, meaning that only the link is utilized.
Not however that your handler function needs to return false to ensure these links aren't used when normally clicking.
EDIT:
Felt this could use an example:
<a href="/Whatever/Wherever.htm" onclick="handler(); return false;" />
link text
For more info and detailed explanation view my answer in another post.
Possibly, I could provide two links each time, one firing the javascript and another being a real link that would allow for middle click.
I presume, one of them would have to be an image to avoid overloading the index.
The onclick event won't be fired for that type of click, so you need to add an href attribute which would actually work. One possible way to do this by adding a #bookmark to the URL to indicate to the target page what the required state is.

Categories

Resources