How can I put a button in the down state? - javascript

Suppose I have a button, which goes into a down state when someone clicks on it, but before the mouse is released.
Now suppose instead that someone presses the 'a' key, I want the button to go into the down state, until the key is released, at which point it is triggered. Is this possible?

After dooing some research here is the final answer I got:
You can trigger mousedown or mouseup events on a button element using keyup and keydown
if your button is programmed to change its style according to these events than you are good to go.
See this fiddle example: http://jsfiddle.net/FwKEQ/15/
Note that if you use jQuery's UI components than it does work. But for standard buttons there is no way that you can move them to their pressed state using javascript
html:
<button id="jQbutton">Press 'A' to move me to pressed state</button>
Javascript:
<script>
$( "#jQbutton" ).button();
$(document).keydown(function(event) {
if ((event.keyCode === 97)||(event.keyCode === 65))
$("#jQbutton").mousedown();
});
$(document).keyup(function(event) {
if ((event.keyCode === 97)||(event.keyCode === 65))
$("#jQbutton").mouseup();
});
</script>
EDIT:
There might be a hack that we could utilize:
using accesskey for the button element and then try to simulate the accesskey press (that i am not sure if possible)
here is where i'm at so far http://jsfiddle.net/FwKEQ/28/
EDIT 2:
So looking further into this topic i have found the following:
Default buttons (without styles) are rendered by the OS, I was not able to find a formal proof for that but if you try to load the same page using a mac OS you'll get mac OS style buttons while in windows you will get the "ugly" gray button.
Because the default buttons are rendered by the OS they comply to OS events meaning events that are sent by the browser and are trusted.
this is not true for custom styled buttons as they comply to CSS an JS to change their appearance on press that is why the JQ button is affected by JS.
so to summarize you would need a trusted press event to fire on a default button to change its style and that cannot be done due to security constraints.
read a bit more about trusted events here: http://www.w3.org/TR/DOM-Level-3-Events/#trusted-events
and if someone could find a formal reference with regards to the default buttons being rendered by the OS please comment or edit this answer.

Unfortunately the rendering of the active state on default buttons neither
is a simple matter of css styling nor can be easily changed by applying
javascript.
An option to do this on default buttons is to use the hotkeys jquery plugin: https://github.com/jeresig/jquery.hotkeys or implement alternative key codes for different browsers.
and to apply 50% opacity to the default button when pressed (to indicate the keydown).
(To me it seems almost perfect ;-) It probably is as good as it can easily get to work across platforms and browsers using default buttons.
jsfiddle DEMO
and the code ...
html:
<button id="test">Test Button</button>
Selected: <span class="selected" id="out"></span>
javascript:
$('#test').click(function () {
fn_up();
});
fn_down = function(event){
$('#test').css("opacity", 0.5);
$('#test').focus();
event.preventDefault();
}
fn_up = function(event){
$('#test').css("opacity", 1);
$('#out').append(" test");
event.preventDefault();
}
//to bind the event to the 'a' key
$(document).bind('keydown','a', fn_down);
$(document).bind('keyup','a', fn_up);
//to get the same effect with the 'space' key
$(document).bind('keydown','space', fn);
$(document).bind('keyup','space', fn2);
In the fiddle I apply it to the space button and the mousedown/up to achieve the same effect with all events (but you could just use it with the 'a' key ... this is a matter of taste).

Here is a jsfiddel that shows how it's done using jQuery: http://jsfiddle.net/KHhvm/2/
The important part:
$("#textInput").keydown(function(event) {
var charCodeFor_a = 65;
if ( event.which == charCodeFor_a ) {
// "click" on the button
$('#button').mousedown();
// make the button look "clicked"
$('#button').addClass('fakeButtonDown');
// do some stuff here...
// release the button later using $('#button').mousedown();
}
});
The button event is triggered when entering "a" in the input field. But as Mark pointed out you need to fake the styling for the clicked button because the browser doesn't do it.
Edit: I'm not sure if you're using jQuery in your project. I just wanted to show that it is possible at all. If it can be done with the jQuery library there is also a way to do it in pure javascript. ;)

Related

JQuery is not triggering atbar button

I am working on a large project and need to fix some accessibility issues.
These is a section which has been generated by https://www.atbar.org/ in a JS format I am not familiar with. The user clicks buttons to change font size, background colour and other html elements to assist them with reading content.
When you click on the buttons with your mouse they work fine. This is an example of how the buttons appear:
<li class=“access-button">
<a title="Decrease Text Size" id="block_accessibility_dec" tabindex=“0">A-</a>
</li>
If I focus my Chrome inspector on the link element I can see there is an event listening for my click:
This appears to trigger the change in font size. I found the code that triggers this click, it is in a JS format that I am not familiar with:
M.block_accessibility = {
init: function(Y, autoload_atbar, instance_id) {
this.defaultsize = M.block_accessibility.DEFAULT_FONTSIZE;
// This event triggers after clicking
Y.all('#block_accessibility_textresize a').on('click', function(e) {
if (!e.target.hasClass('disabled')) {
M.block_accessibility.changesize(e.target);
}
});
// This is the function it runs, it has many cases for all the different buttons.
changesize: function(button) {
Y = this.Y;
switch (button.get('id')) {
case "block_accessibility_dec":
Obviously this is just snippets of the code with comments I added.
What I require is the user to be able to change the font size using just tab and enter, so I added the following JQuery:
$("#block_accessibility_dec").keyup(function(event) {
if (event.keyCode === 13) {
$('#block_accessibility_textresize #block_accessibility_dec').click();
}
});
This is not triggering the change in font size. Yet when I click on the button it does? There is probably a really simple solution here but I've been stuck for ages. I tested the .click() on other elements on the screen and it works for them so the JS is definitely executing.
I have also tested:
$(this).click();
But to no avail.
Try to trigger the click event by the native way:
$('#block_accessibility_textresize #block_accessibility_dec')[0].click();
Source: I tried their demo page together with the chrome inspector and couldn't get the click working with JQuery.
But with the native click event it suddenly worked.
Unfortunately I can't really explain to you, why JQuery doesn't work here. Maybe something with their version (1.11)?
Replace your code with the following code and add the keyup event. This should work when you press the enter key.
Y.all('#block_accessibility_textresize a').on('click keyup', function(e) {
if (e.keyCode == 13 || e.keyCode ==9) {
if (!e.target.hasClass('disabled')) {
M.block_accessibility.changesize(e.target);
}
}
});
You should use the following Jquery:
$('#block_accessibility_textresize #block_accessibility_dec').trigger("click");
Please let me know if this doesn't work.

VueJS - How to detect Ctrl+V?

I've already seen the answers to this question, but it's not the solution I need, since it's for jQuery, and I need something for vue.js.
So far, I was able to detect single character presses using the ff. code:
export default {
name: 'game',
data () {
return {
allowInput: false,
disabledKeys: ['ArrowLeft', 'Home', 'Control']
}
},
methods: {
keymonitor: function (event) {
console.log(event.key)
if (this.disabledKeys.indexOf(event.key) >= 0) {
event.preventDefault()
this.allowInput = false
// alert('not allowed')
} else {
this.allowInput = true
}
},
checkAnswer () {
if (! this.allowInput) {
alert('the key(s) you pressed is/are not allowed')
}
} /* END checkAnswer */
} /* END methods */
} /* END export default */
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.2/vue.min.js"></script>
<input id="typeBox" ref="typeBox" autocomplete="off" placeholder="Type here..."
#keydown="keymonitor" #keyup="checkAnswer()" />
The code above successfully prevents the textbox from accepting ArrowLeft, Home, and Control key presses.
The problem:
I'm trying to figure out how to detect Ctrl+V, because I want to prevent paste action in my text box. Does anyone know how to do this? Thanks in advance.
To detect two keys, Vue provides modifier keys, For example to detect Alt+C, you can simply do:
<input #keyup.alt.67="YourFn">
Similarly for Ctrl+V, you can do:
<input #keyup.ctrl.76="YourFn">
As I can see here, ASCII code for Ctrl+v is 22, so you should be simply able to do :
<input #keyup.22="YourFn">
you can check the js fiddle link for the same
keyup: function(event){
if(event.keyCode == 86 && event.ctrlKey){
// do something here
}
}
https://jsfiddle.net/neelkansara28/wh61rby8/16/
I'm a little late to the party here but for anyone coming here with this same question, there is really no need for anything fancy that is not built into Vue itself. If you don't want to read through all of this
Here is a sandbox with a working example to play with
As the accepted answer says, vue has it's own event listeners as documented here
It also does not require key codes, specifically, to work. So in your case, it will accept the letter v
Below is an example of a vuetify component (although this will work with pretty much any element):
<v-text-field
v-model="textField"
#keydown.prevent.ctrl.v=""
#keydown.prevent.meta.v=""
#click.prevent.right.exact=""
/>
Here is the breakdown of the #stuff that you see there:
To prevent key combos like ctrl/cmd + v:
In the case of combos, in order to make it work, you'll have to listen to keydown instead of the alternatives
To account for Windows, you'll need to use #keydown.prevent.ctrl.v=""
To account for Mac, you'll need to use #keydown.prevent.meta.v=""
#keydown listens for the keydown event
.prevent automatically applies event.preventDefault()
.ctrl/.meta are the modifier keys you're listening for
the meta key is the CMD key on Mac and Windows key on Windows
v is, of course, the other key we are listening for
the empty "" just means we're not giving it a function to run. if you want to do anything additional, you can just simply reference a function here. like: #keydown.prevent.meta.v="doSomethingElse"
If you also want to prevent the right-click (context) menu: #click.prevent.right.exact=""
#click will listen to the click event.
.right is the modifier to listen for right-clicks only
.exact makes sure that no other modifiers are accepted. Without this, someone could press shift + right-click and the context menu would appear as normal. In this case, .exact makes sure we're doing something on any version of right-click

Shortcut keys for Javascript game GUI

I've been making a simple javascript based OOP text game that uses string replacement and variable adjustments tied to button .onclick events. I've been asked to add hotkeys for easier access, and I've been struggling with how to do it.
First I tried using the JSQuery hotkeys script and the .bind command, but that seemed like it would be very time consuming as I'd have to recode every .onclick as a hotkey, and even with unbind, it was firing off every event tied to the key on the script.
I feel like the best way to do would be if I could code the keys to the gui, i.e. if when you pressed "1", it activated the .onclick of button 1, that way the hotkey would be static (except when the button is disabled), but I've no idea how to do that. I've just been using html buttons, (i.e. input type="button" value="" disabled="disabled" id="button1"), I suspect I'd need something more sophisticated?
Thanks in advance for any help, google has been useless.
[EDIT - General description of code]
The way the game works is very simple, via the calling of functions as new events with different text/buttons (and different onclick events tied to those buttons). As an example, the start screen code is:
function startScreen() {
$(document).ready(function () {
$('#text').html("Game title and info");
$('#button1').val("Start Game");
$('#button1').attr("disabled", false);
$("#button1").one("click", function () {
textClear();
buttonClear();
nameScreen();
});
$("#button2").val("Load Game");
$('#button2').attr("disabled", false);
$("#button2").one("click", function () {
textClear();
buttonClear();
loadData();
});
$("#button6").val("Settings");
$('#button6').attr("disabled", false);
$("#button6").one("click", function () {
textClear();
buttonClear();
settingsScreen();
});
});
}
Since the code executed by button one changes between functions, what the hotkey does as well, which was my problem with using the JQuery library code.
When a key is pressed then the event onkeypress is fired. This event provides some values like:
keyCode
charCode
which
So you could do something like:
window.onkeypress = function (event) {
// the keyCode value for the key 1 is 49, for the key 2 is 50
if (event.keyCode == 49) {
// execute the same code as clicking the button 1
console.log("The key 1 was pressed.");
} else if (event.keyCode == 50) {
// execute the same code as clicking the button 2
console.log("The key 2 was pressed.");
}
};
Now, when a user visits your website he could press the keys 1 or 2 on the keyboard and fire the same logic as clicking the buttons "1" and "2" (being something like <input id="button1">) with the left mouse taste.
If you have really a lot of hotkeys then this would be also tedious to type, but without knowing your code I can hardly give you a complete solution. I hope my answer can give you some idea how to proceed further.
EDIT:
Further reading on the topic:
http://unixpapa.com/js/key.html

Toggle select2 from different element

We have a select2 dropdown in a row (just a div) and we need to be able to click that entire row to trigger the dropdown. I have no problem showing it, but trying to hide it has become a problem, and I'm wondering if my logic is flawed somewhere. select2 AFAIK doesn't have a toggle method on the version we're on, so I have to manually use it's open and close methods. This is what I tried.
$('[data-variable-type=select]').on('click', function(e){
e.stopPropagation();
var _dropdown = $(this).find('div.interface_dropdown');
if( _dropdown.hasClass('select2-dropdown-open') ) {
$(this).find('select.interface_dropdown').select2('close');
}
else {
$(this).find('select.interface_dropdown').select2('open');
}
});
This causes it to open properly, but when you click to close it, it closes on mousedown but reappears on mouseup.
Is there someway I can get it toggling properly?
Will you post relevant HTML? It's hard to understand what you're doing without seeing content.
$('[data-variable-type=select]').on('click', function(e){
e.stopPropagation();
var _dropdown = $(this).find('div.interface_dropdown');
if( _dropdown.hasClass('select2-dropdown-open') ) {
_dropdown.removeClass('select2-dropdown-open');
_dropdown.select2('close');
} else {
_dropdown.select2('open');
_dropdown.addClass('select2-dropdown-open');
}
});
It looks like you forgot to add/removethat class, maybe this will work better? Again, I'm kind of feeling around in the dark here without seeing your content.
if( _dropdown.hasClass('select2-dropdown-open') ) {
$(this).find('select.interface_dropdown').select2('close');
}
in later versions of select2 (3.3+ iirc) this will never get triggered because when opened select2 creates a transparent mask over the entire browser and listens to click events. when the mask is clicked currently opened select2 is closed. this was the only reliable way to close a select2 when the user is ready to do something else.
The proper way is:
$('select').data('select2').toggleDropdown()

Boxee Box: How to trigger Home-Button in Boxee Browser (KEYBOARD_MODE)?

How can I get the back/home button working in boxee box browser? F.e. I want to open a menu if user clicks enter and want to close it with back button?
I was just writing a function which triggered all received keycodes in the boxee browser (browser in boxee.KEYBOARD_MODE). I received every keyboard key, but I couldn't get an event for the play/pause button.
If I was pressing the back/home button, the application shows the dialog to close the browser and I didn't receive a keycode too. Are these buttons functional buttons which cannot be modified?! Or is there a way to override the buttons behaviour?
Best, K
You can actually control what those buttons do by setting the relevant callbacks in your controller file.
You would be interested in onKeyboardKeyBack, onPause and onPlay.
It's pretty well documented here:
http://developer.boxee.tv/Control_Script_Context
http://developer.boxee.tv/JavaScript_API#Keyboard_Mode
For example, you can override the behavior of the back button using something like:
boxee.onKeyboardKeyBack = function() {
var pathname = browser.execute('window.location.pathname');
switch (pathname) {
case 'boxee':
browser.shutdown();
break;
default:
browser.back();
break;
}
};
Note that it seems like browser.execute() will only return strings, so you can't do things like:
var location = browser.execute('window.location');
alert('location.pathname');
and just as an update, with the new api it is now possible to trigger menu/back button and play/pause button without the native overlay!
http://developer.boxee.tv/JavaScript_API#Keyboard_Mode

Categories

Resources