beewuu beewuu - 15 days ago 5
Javascript Question

code runs correct on console but not in actual code

I am using google charts and am manually positioning the vaxis titles by

$($('text').filter(':contains("Recurrence Interval")')[0]).attr('x', '220');
$($('text').filter(':contains("Hazard Score")')[0]).attr('x', '50');
$($('text').filter(':contains("Hazard Score")')[0]).attr('y', '225');


The thing is that the first line works 100% fine. The next two lines don't seem to work when in my code. However when I run the bottom two lines in my console, it works. This is all wrapped by a google chart setOnLoadCallBack function so the charts should have been loaded already.

Answer

need to wait for the chart's 'ready' event to fire,
before making modifications

set the event listener before drawing the chart, e.g.

var chartDiv = document.getElementById('chart_div');
var chart = new google.visualization.BarChart(chartDiv);

google.visualization.events.addListener(chart, 'ready', function () {
  $($('text').filter(':contains("Recurrence Interval")')[0]).attr('x', '220');
  $($('text').filter(':contains("Hazard Score")')[0]).attr('x', '50');
  $($('text').filter(':contains("Hazard Score")')[0]).attr('y', '225');
});

chart.draw(data, options);

if animation is being used, listen for the 'animationfinish' event instead