Custom Tooltips

Jump to solution
dtod
Community Contributor

Canvas has a tooltips framework that appears to exist in both jquery and react. I am assuming the latter is the path going forward, but I would like to hook into it to add our own tooltips, e.g. give explanations where we've changed something or links to relevant documentation about LTIs or custom roles and permissions.

I've built my own tooltip framework, but life would be much easier if I could just hook into the Canvas one.

Adding 

data-tooltip title="some descriptive text that I want"

To any element almost works, but appears to use jquery, and the complete styling isn't applied.

Does anyone have any ideas how this might be done?

0 Likes
1 Solution
dtod
Community Contributor
Author

I'm going to answer my own question. The code below is very lightly tested, but it seems to work.

function addToolTip(el, textToAdd){
	el.setAttribute('data-tooltip','top');
	el.title=textToAdd;

	var observer = new MutationObserver(setToolTipStyle);

	// observe the element for the specific attribute modification
	observer.observe(el, {subtree: true, attributeFilter: ['aria-describedby']});
}

function setToolTipStyle(mutations){
	for(var mutation of mutations){
		// canvas has code that converts the title to aria-describedby when data-tooltip is set
		// aria-describedby is the ID of a dynamically-created div 
		// which Canvas code places near the element with the tooltip
		if (mutation.attributeName = 'aria-describedby' && mutation.target.getAttribute('aria-describedby') != null){
				var targetId = mutation.target.getAttribute('aria-describedby');
				var targetEl = document.getElementById(targetId);
				
				// this code tweaks the tooltip display because the default it not good
				targetEl.style.padding='0.75rem';
				targetEl.style.fontSize='0.875rem';
				targetEl.className = targetEl.className.replace(" horizontal","");
				
				// reposition
				var newtop = (Number(targetEl.style.top.replace('px','')) - mutation.target.offsetHeight - 5) + 'px';
				targetEl.style.top = newtop;
				
				// not sure about this bit below. I was trying to base it off the width of the element
				var newleft = (Number(targetEl.style.left.replace('px','')) - (mutation.target.offsetWidth/5)) + 'px';
				targetEl.style.left = newleft;
		}
	}
}

// assuming targetEl is some element obtained from document.getElementById
addToolTip(targetEl,'this is helpful');

View solution in original post