I want to have a dynamic tooltip inside my chart with buttons inside it.
Look like what i want is to create a custom tooltip. Once created, i try to hover over i but i can't.
At first i thought it was impossible so i decided to create my very own custom tooltip which didn't turn out well. I created my own html component and a function to show this component, the function was fired when i hovered over a dot in the chart. The result was awful, the tooltip was blinking all the time so I headed back to the custom tooltip option chart.js provides. However i haven't found a way to keep the custom tooltip open when hovering over it.
The code i am using :
tooltips: {
enabled : false,
custom : function(tooltipModel){
var tooltipEl = document.getElementById('custom-tooltip')
//if tooltip component doesn't exist yet
if(!tooltipEl){
tooltipEl = document.createElement('div')
tooltipEl.id = 'custom-tooltip'
tooltipEl.innerHTML = '<table></table>'
document.body.appendChild(tooltipEl)
}
//making component opacity the same as in model
if(tooltipModel.opacity === 0){
tooltipEl.style.opacity = 0;
return;
}
tooltipEl.classList.remove('above','below','no-transform',)
if(tooltipModel.yAlign){
tooltipEl.classList.add(tooltipModel.yAlign)
}else{
tooltipEl.classList.add('no-tranform')
}
function getBody(bodyItem){
return bodyItem.lines
}
//adding information inside component
if(tooltipModel.body){
var titleLines = tooltipModel.title || []
var bodyLines = tooltipModel.body.map(getBody)
var innerHTML = '<thead>'
titleLines.forEach(function(title){
innerHTML += '<tr><th>' + title + '</th></tr>'
})
innerHTML += '</thead><tdboy>'
bodyLines.forEach(function(body,i){
var colors = tooltipModel.labelColors[i]
var style = `
background : ${colors.backgroundColor};
border-color : ${colors.borderColor};
border-width : 2px;
`
var span = '<span style="'+style+'"></span>'
innerHTML += '<tr><td>' + span + body + '</td></tr>'
})
innerHTML += '</tbody>'
innerHTML += '<button>button inside tooltip</button>'
var tableRoot = tooltipEl.querySelector('table')
tableRoot.innerHTML = innerHTML
}
var position = this._chart.canvas.getBoundingClientRect()
tooltipEl.classList.add('custom-tooltip')
tooltipEl.style.opacity = 1
tooltipEl.style.left = position.left + window.pageXOffset + tooltipModel.caretX + 'px'
tooltipEl.style.top = position.top + window.pageYOffset + tooltipModel.caretY + 'px'
// tooltipEl.style.pointerEvents = 'none'
}
I have a working custom tooltip on : https://jsfiddle.net/wL179b2p/
I only need something that prevents the tooltip from closing when not hovering over it.