I'm trying to get the focus method (touch, mouse or keyboard) on links setting a data-attribute.
$(function() {
var i,
r = document.getElementsByTagName("a")[0];
if ("ontouchstart" in window) {
document.addEventListener("touchstart", function(event) {
i = "touch";
}, true);
}
else {
document.addEventListener("mousedown", function(event) {
i = "mouse";
}, true);
}
document.addEventListener("keydown", function(event) {
i = "keyboard";
}, true);
})
The problem is that I only get results writing the last part in jQuery:
$("a").focus(function() {
$(this).attr("data-focus-method", i)
})
$("a").blur(function() {
$(this).removeAttr("data-focus-method")
})
And I want to write the whole code in plain JavaScript. I've tried the way below:
r.addEventListener("focus", function() {
r.setAttribute("data-focus-method", i);
});
r.addEventListener("blur", function() {
r.removeAttribute("data-focus-method");
});
But it doesn't work. Can somebody help me please?
r = document.getElementsByTagName("a")[0]when you mention "on links" - ie your text implies multiple/all links but your code indicates first link (which is a bit strange in itself). If you actually have something likefor (var idx in document.getElementsByTagName("a")) { var r = document.getElementsByTagName("a")[idx]then that's your problem - r will have changed by the time it hits the event listener, hence the use ofthis.[0]I get the "r.addEventListener is not a function" error message.getElementsByTagName()returns a nodeList which you need to iterate through and calladdEventListeneron each individual element[0]- it's more that does your real code use[i](or similar)?