While messing with the dojo tooltip widget in one of our applications, I had the need to dynamically create a widget. Below is a sample statement of dynamically creating a tooltip widget.
dojo.widget.createWidget('tooltip', { caption: 'what you want the tooltip to say', connectId: 'target_id_to_attach_tooltip' });
However, this is not complete because we need to attach it to the body of the document like this:
var new_tooltip = dojo.widget.createWidget('tooltip', { caption: 'what you want the tooltip to say', connectId: 'target_id_to_attach_tooltip' }); document.body.attachChild(new_tooltip.domNode);
You’ll notice that the return value of dojo.widget.createWidget is an object and when we attach it to the body of the document, we use the domNode property of that object.
There is one more potential problem with dynamically creating these widgets. Let’s say that we have a dynamic table and each row of the table contains the target id for each tooltip. If the table gets reloaded with new data (rows have new ids), the old tooltips remain appended to the body. No big deal of you don’t mind a little trash left behind, but the problem comes into play when you load data back into that dynamic table that may have previously existed and generate a whole new set of tooltips to go along with it. Now you may have two or more of the same tooltip appended to the body that belong to the same target id. Some browsers might be fine with this and some might choke. To prevent these duplicates, we use the following code for each new tooltip widget that is created:
function createTooltip(target_id, content) { //prepending 'tt_' to distinguish between target and tooltip id's var obj = document.getElementById('tt_'+target_id); if(obj != null) obj.parentNode.removeChild(obj); var tooltip = dojo.widget.createWidget('tooltip', { caption: content, connectId: target_id }); tooltip.domNode.id = 'tt_'+target_id; document.body.appendChild(tooltip.domNode); }
You might notice that we are actually adding an ID to the tooltip. This allows us to check in the future if that tooltip has already been created. If it has, the code above will destroy it and create a new tooltip in its place. This should assist those searching for answers about dynamically creating dojo tooltip widgets.
