Forwarding javascript attribute events to different handler/type
-
07-07-2019 - |
Question
I'm currently trying to set up a web page for a touch screen computer, and have noticed that (with my fat fingers) that onclick events are really hard to trigger, as the surface area of my finger generally causes the cursor to move while I "click".
The solution I want to use is forwarding onmousedown events to onclick. How can I make this work?
The best answer would be along the lines of:
<input type="radio" onmousedown="this.onclick()"/>
(but of course in a working condition)
EDIT: My specific example is for radio buttons - when one is checked the others are unchecked; I don't want to have to replicate this behaviour in a custom event when the browser gives it to me for free.
NOTE: Having edited, and received feedback, I think that perhaps I might be on the wrong track... perhaps it's not the "click" function on a radio button that actually does the selection: new suggestions welcome ...
Solution
Ok, after your edits it becomes clearer - what you want to do is to simulate a user clicking the control when the mousedown
event is fired.
Two options:
- You can fire the DOM event - this tutorial on DOM events discusses this (see the Manually firing events section); Firing Javascript Events covers similar ground.
- Set
onmouseout="this.checked = true;"
, i.e. clicking the radio button "checks"/selects the radio button.
OTHER TIPS
Why not just handle the mousedown
event?
I know you didn't mention it in the question, but if you happen to be using jQuery, it'd be really really easy:
$().live('mousedown', function() { this.click(); });
Maybe this works for you
document.getElementById("yourinput").onmousedown = function() {
this.click();
}
Additionally you could style your input buttons/fields to be a little bigger, for better accessibility via the pointer.
It's better to have a single function to handle both events, e.g.
var function = foo(e) {
...
};
<input onclick="foo();" onmousedown="foo();"/>
Better still use unobtrusive JavaScript, e.g. (if you were using YUI):
<input id="input-el"/>
var function = foo(e) {
...
};
var Event = YAHOO.util.Event;
Event.on('input-el', 'click', foo);
Event.on('input-el', 'mousedown', foo);