Reputation: 11
What I want my code to do is when I pass with my mouse on my text, the next letters of the alphabet appear. I created the function nextLetter
but it doesn’t work.
var conteneur = document.querySelector('.texte2')
var textBalise = conteneur.textContent.replace(/(\S)/g, '<span class = x>$1</span>')
conteneur.innerHTML = textBalise
var $spans = document.querySelectorAll('span')
const ch = 'a'
function nextLetter(ch) {
if (!ch.match(/[a-zA-ZäöüßÄÖÜ]/i)) return ch;
else if (ch === 'Z') return 'A';
else if (ch === 'z') return 'A';
return String.fromCharCode(ch.charCodeAt(0) + 1);
}
for (var $span of $spans) {
$span.addEventListener('mouseover', (e) => {
console.log(nextLetter)
});
}
Upvotes: 1
Views: 39
Reputation: 28611
Your issue is that you're not passing the character under the mouse to the nextLetter
function.
console.log(nextLetter)
will output the definition of the function, not call it - you need to add ()
to call the function.
The letter under the cursor is: e.currentTarget.textContent
, giving
for (var $span of $spans) {
$span.addEventListener('mouseover', (e) => {
console.log(nextLetter(e.currentTarget.textContent))
});
}
Put together, your code becomes:
var conteneur = document.querySelector('.texte2')
var textBalise = conteneur.textContent.replace(/(\S)/g, '\<span\>$1\</span\>')
//console.log(textBalise)
conteneur.innerHTML = textBalise
var $spans = document.querySelectorAll('span')
// not used: const ch = 'a'
function nextLetter(ch) {
if (!ch.match(/[a-zA-ZäöüßÄÖÜ]/i)) return ch;
else if (ch === 'Z') return 'A';
else if (ch === 'z') return 'a';
return String.fromCharCode(ch.charCodeAt(0) + 1);
}
for (var $span of $spans) {
$span.addEventListener('mouseover', (e) => {
//console.log(e.currentTarget.textContent)
console.log(nextLetter(e.currentTarget.textContent))
});
}
<div class='texte2'>This is a test</div>
Upvotes: 1