I have a function which detects when user press TAB key. Main goal is to check if user navigates to anchor elements. I want to remove tittle attribute from it, but when he press tab again and go to another element, I want to restore title back. At this point I'm removing it on focus and set data-title property. I thought maybe I can restore title from data-title attribute on blur. Is there any way to achieve it?
function checkTabPress (e) {
let activeElement
if (e.keyCode === 9) {
activeElement = document.activeElement
if (activeElement.tagName.toLowerCase() === 'a') {
activeElement.setAttribute('data-title', activeElement.getAttribute('title'))
activeElement.removeAttribute('title')
}
}
}
const wrapper = document.getElementById('wrapper')
wrapper.addEventListener('keyup', checkTabPress)
a:focus {
color: red;
}
<div id="wrapper">
<a title="link 1" href="">link 1</a>
<a title="link 2" href="">link 2</a>
<a title="link 3" href="">link 3</a>
<a title="link 4" href="">link 4</a>
</div>
Check this:
function checkTabPress (e) {
let activeElement
if (e.keyCode === 9) {
activeElement = document.activeElement
if (activeElement.tagName.toLowerCase() === 'a') {
activeElement.setAttribute('data-title', activeElement.getAttribute('title'))
activeElement.removeAttribute('title')
}
}
}
const body = document.querySelector('body')
body.addEventListener('keyup', checkTabPress)
body.addEventListener("blur", function( event ) {
var title = event.target.getAttribute('data-title');
if (title) {
event.target.setAttribute('title', title)
event.target.removeAttribute('data-title')
}
}, true);
We simply added a blur event and do the opposite that you are doing to remove the title.
You could simply restore titles on all anchors with each tab press.
function checkTabPress(e) {
let activeElement
if (e.keyCode === 9) {
// restore titles on all anchors
const anchors = document.querySelectorAll('a'); // could be reduced with a parent selector
anchors.forEach(function(anchor) {
anchor.setAttribute('title', anchor.getAttribute('data-title'))
anchor.removeAttribute('data-title')
})
activeElement = document.activeElement
if (activeElement.tagName.toLowerCase() === 'a') {
activeElement.setAttribute('data-title', activeElement.getAttribute('title'))
activeElement.removeAttribute('title')
}
}
}
const wrapper = document.getElementById('wrapper')
wrapper.addEventListener('keyup', checkTabPress)
a:focus {
color: red;
}
<div id="wrapper">
<a title="link 1" href="">link 1</a>
<a title="link 2" href="">link 2</a>
<a title="link 3" href="">link 3</a>
<a title="link 4" href="">link 4</a>
</div>