So I have a textarea containing text. I want to be able to display a tooltip when my mouse is hovered a certain word inside the textarea.
Is this possible at all? I would prefer to see a solution that doesn’t use any third party javascript libraries.
Thanks!
If you’re willing to use a “richtext” field (eg
contentEditableanddesignMode), you can wrap the word with a<span>and attachmouseoverandmouseoutevents to it. The big drawback with this approach is that “richtext” features that you may not want can be invoked with keyboard shortcuts in some browsers even if you don’t provide an interface for them, and you’ll need to filter those styles either while editing or after saving to a<textarea>.Alternatively, you can have a hidden (but not
display: none, as this will prevent accurate measurement)<div>* and update its content as the<textarea>changes, wrap the word with a<span>as in the option above, and display the tooltip if the cursor position’s offset relative to the<textarea>is within bounds that would be over the<span>relative the hidden<div>. To determine position you’d probably want to start amousemoveevent observer if there is amouseoverevent on the<textarea>, and stop themousemoveevent if there is amouseoutevent on the<textarea>.* Note: In order to ensure correct positioning, this
<div>should have exactly the same font, text, line and dimensional styles as the textarea, and when mirroring the content you’ll need to escape HTML special characters (&,<and>), as well as convert new lines to<br>tags.