Problem is when I press a key over a radio button, element MyFunc
fires twice - once for onkeypress
event, another time for "click" event.
Question "Why?" I need to handle this by two different ways, but now I can not recognize what initial event was. When I click a mouse it fires just for "click" event.
<ul>
<li>
<input type="radio" onkeypress="MyFunc(event, this)" onclick="MyFunc(event, this)" name="myList" id="MyId_1" />Topic 1
<input type="radio" onkeypress="MyFunc(event, this)" onclick="MyFunc(event, this)" name="myList" id="MyId_2" />Topic 2
</li>
</ul>
function MyFunc(e, obj) {
alert(e.type); // alerts "keypress" and then "click"
// Do my stuff
}
If 2 events are being fired during pressing a key then check event.detail
property in onClick
function.
if event.detail = 0
then it means that mouse was not clicked on that element and we can ignore it.
event.detail
It can be done and without resorting to frameworks which are always bulky and slow. The trick is to record which event happened at what point in time and then on top of that to work within a time frame. When you trigger the keypress
event the click
event is triggered immediately afterwards, here is a list of how quickly the click
event is triggered after the keypress
event...
Chrome 39.0: 0ms
Firefox 31.0 ESR: 18~20ms
IE 11: 2~4ms
Opera 12.1: 0ms
Chrome and (real) Opera don't wait, IE is reasonably quick and Firefox takes it's time so-to-speak; the range to work with (at least on my system) is 0~20 ms. Programmatically I'll set the limit to 50ms for people still using junky computers that are too busy with the 150 useless processes in the background.
Note you'll have to utilize the window
global level events though this seems to work reliably for me in all the browsers that I mentioned.
var option = new function() {this.name = '';}
window.onclick = function(event)
{
option.clickDate = new Date().getTime();
}
window.onkeypress = function(event)
{
option.keyCode = event.keyCode;
option.keyCodeDate = new Date().getTime();
}
function MyFunc(e,obj)
{
if (option.keyCodeDate && option.clickDate &&
(
(option.clickDate - option.keyCodeDate)>=0 &&
(option.clickDate - option.keyCodeDate)<51)
{alert('keypress event');}
else {alert('click event');}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With