+ Start a Discussion
Andrew Aldis 15Andrew Aldis 15 

Java script runs prior to DOM changes and is unable to find a HTML canvas component inside a lighting tab,

I am creating a lightning component and am having trouble with the order that the Java script runs.  I have some <canvas></canvas> in a lightning tab.  when the tabs are changed it calls some javascript which cannot find the canvas on the first time I select a tab.  After I select the tab and go back to it it works fine.  I am using charts.js as well, but I do not think that is the issue.  How can make sure that the canvas component renders prior to the javascript running?  My code is below.

Lightning CMP:
<lightning:tabset class="tabs" variant="scoped" onselect="{! c.tabSelect }">
<lightning:tab label="RETAIL" id='retail'>
<div class="asOfGraph" >as of {!v.asOfGraph}</div>
<div class="graph" >
<canvas aura:id="barChart" id="barChart" class="barChart" />
<lightning:tab label="DCIO" id="dcio">
<div class="asOfGraph">as of {!v.asOfGraph}</div>
<div class="graph" id="dcioGraph" >
<canvas aura:id="dcioChart" id="dcioChart" class="dcioChart" />
<lightning:tab label="RECORDKEEPER" id='recordkeeper'>
<div class="asOfGraph">as of {!v.asOfGraph}</div>
<div class="graph" id="recordKeeperGraph">
<canvas aura:id="recordChart" id="recordChart" class="recordChart"/>
<lightning:tab label="ASSETS" id='assets'>
<div class="asOfGraph">as of {!v.asOfGraph}</div>
<div class="graph" id="assetsGraph">
<canvas aura:id="assetsChart" id="assetsChart" class="assetsChart"/>

tabSelect: function (cmp, evt, help) {
var tab = evt.getParam("id");
console.log('tab is ' + tab);
if (tab == 'assets') {
help.createVerticalGraph(cmp, evt);
//cmp.set("v.assetsSet", true);
} else if (tab == 'dcio') {
help.createBarGraph(cmp, evt);
// cmp.set("v.dcioSet", true);
} else if (tab == 'recordkeeper') {
help.createBarGraph(cmp, evt);
// cmp.set("v.recordkeeperSet", true);
Raj VakatiRaj Vakati
Are you using any JS libraries? Use after script load methid of ltng:required 

please refer this link to understand the component life cycle 

Andrew Aldis 15Andrew Aldis 15
I am using Chart.js, and have the init method called after the library loads.  It is working well upon the initial load of the page, the problem happens when I change tabs, the canvas element on the new tab is not rendered before the code is run, but only on the first time I go to a particular tab.