As some of you know, my wife's been in grad school online at Harvard Extension for some months now.
(She's going for a Masters in Digital Media Design - and she's doing great!)
She just finished a javascript course.
As I've never taken javascript formally, but am decent at figuring out just about any scripting language, I decided to review her various assignments and see if I could teach myself some javascript.
Within one of the projects, it's required to turn a 'box' of text within a div into spanned words individually. Each word would then have a class ("word") added an individual ID ("word##"), and change style when hovered over, removing the style after hover ends.
The below, in combination with code not shown, works 100%
It's based inside a loop (which increases i, and 'word_count')
'my_div_element' is the div box with the words in it to work with, and is defined earlier than shown.
// Thanks to W3Schools
// https://www.w3schools.com/js/js_htmldom_nodes.asp
// create span element
var to_span = document.createElement("span");
// set span class to word
to_span.setAttribute("class", "word");
// set span id to word + ##
var IdNum = "word" + word_count
to_span.setAttribute("id", IdNum);
// create text node with current word, trimming extra space and \n, from my array plus a space
var my_word = document.createTextNode(array_transcript[i].trim() + " ");
// append current text to my current span
to_span.appendChild(my_word);
// append my new span to my trascriptText div element
my_div_elem.appendChild(to_span);
document.getElementById(IdNum).addEventListener("mouseover", MouseHover);
document.getElementById(IdNum).addEventListener("mouseout", MouseExit);
My question is regarding the last two lines, the event listeners: According to w3schools and a few other sites that describe 'addEventListener', I should be able to attach the event listener to an 'element'.
Though 'document' works in my code, it's the only working solution I can find.
Is there not a more efficient means? Must I really attach it to the whole document+getelementid(name)?
How, if I can, would I go about attaching it to my specific span element without using the 'document' element first?
I've tried;
to_span.id.addEvent....
my_div_elem.to_span.id.addEvent...
getElementById(IdNum).addEvent...
A few others I can't remember now.
Most return 'blah' is not a function.
Any more experienced javascripters out here give me a more efficient working example of how to get the 'element' using the variables I already have in the loop? (I've not tried 'this', but am somewhat familiar with it (somewhat, 'this' still remains confusing to me at times)))