Perhaps this solution could be beneficial:
let doc = document, bod = doc.body;
function E(element){
return doc.getElementById(element);
}
function inArray(value, array){
for(let i=0, len=array.length; i<len; i++){
if(array[i] === value){
return true;
}
}
return false;
}
function wow(inputString, outputElement, beforeArray, afterArray){
let stringArr = inputString.split('');
for(let i=0, length=stringArr.length; i<length; i++){
(function(i){
let spanElm = doc.createElement('span'), text = stringArr[i];
spanElm.innerHTML = text;
spanElm.onmouseover = function(ev){
let event = ev || event;
let relatedTarget = event.relatedTarget;
while(relatedTarget && relatedTarget !== spanElm){
relatedTarget = relatedTarget.parentNode;
}
if(relatedTarget !== spanElm && inArray(text, beforeArray) && afterArray[beforeArray.indexOf(text)]){
spanElm.innerHTML = afterArray[beforeArray.indexOf(text)];
}
};
spanElm.onmouseout = function(ev){
let event = ev || event;
let relatedTarget = event.relatedTarget;
while(relatedTarget && relatedTarget !== spanElm){
relatedTarget = relatedTarget.parentNode;
}
if(relatedTarget !== spanElm){
spanElm.innerHTML = text;
}
};
outputElement.appendChild(spanElm);
})(i);
}
}
The custom wow
function generates spans with backward compatible onmouseenter
and onmouseleave
Events automatically added. To style these spans, you can assign sp.className = 'over';
on onmouseover
and sp.className = 'default';
on onmouseout
, with CSS already configured accordingly. For unique styling, additional arrays would need to be included in the wow
function. Within onmouseover
and onmouseout
, sp
could also be referenced as this
.
// appends to id='someId'
wow('Just Adding Some Random Text', E('someId'), ['J', 'T'], ['M', 'S']);