Reputation: 1
The code below attaches event handlers for clicks, but is not working for keyboard events. I don't want just the document.keypress
but specific class elements for keyboard events. So I have 'test' written out which works for mouse clicks fine, but not for any of the keyboard events.
function test(className, fnCall, eventToApply){
if(typeof document.getElementById('x').getElementsByClassName(className) !='undefined') {
var els = document.getElementById('x').getElementsByClassName(className);
for(var i = 0; i < els.length; i++) {
if(els[i].addEventListener) { //Undefined for keypress events
els[i].addEventListener(eventName, function(e) { fnCall(e); }); }
else { //Hardcode for testing
els[i].onclick = function(e) { fnCall(e); };
els[i].onkeypress = function(e) { fnCall(e); } //doesn't work!
}
}
The document onkeypress works though, but I am unable to set up individual element handlers on document ready or the keypress itself.
document.addEventListener('keypress', function(event){
//This works, but setting up events for each class type element doesn't work for keypress
})
In other words, is there an equivalent to do the below, without using JQuery:
document.addEventListener('keypress', function(event){
//This works in Jquery
$('.customClass-'+ event.keycode).click();
});
document.addEventListener('keypress', function(event){
//This doesn't register, says undefined for any event or attachEvenHandler/attachEvent
test('.class'+event.keycode, myFunction() , 'keypress');
});
Upvotes: 0
Views: 1910
Reputation: 146
You can use this
document.addEventListener('keypress', function(event){
var elements = document.getElementsByClassName("customClass-" + event.keycode);
for (var i = 0; i < elements.length; i++) {
elements[i].click();
}
});
w3school documenations
Upvotes: 0