Integrating .js to Vaadin - Access div in DOM

Hello to Vaadin developers,

I’am looking forward to new Vaadin 7 and tried new beta1 to integrate highchart.js to Vaadin 7. It seems to be very easy… great work!

But currently I have got a problem due to loading the chart. The chart is only shown after a second reload because highchart.js cannot find the belonging div-Element. (myJSComponent)

Here is my code:


##java
package com.example.javascriptdemo;

public class JavascriptdemoUI extends UI {

	private static final long serialVersionUID = 2169060678592185114L;

	@Override
	public void init(WrappedRequest request) {
		this.setId("myJSComponent"); // needed for highchart.js
		JsHighChart chart = new JsHighChart();
		addComponent(chart);
	}

}

public class JsHighChartState extends JavaScriptComponentState
{
	private static final long serialVersionUID = -1016346299843904188L;
}

@JavaScript({ "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", "highcharts.js", "js_highchart.js"})
public class JsHighChart extends AbstractJavaScriptComponent
{
	private static final long serialVersionUID = 1913474773889181118L;

	public JsHighChart()
	{
	}

	@Override
	public JsHighChartState getState()
	{
		return (JsHighChartState) super.getState();
	}
}

##javascript
com_example_javascriptdemo_JsHighChart = function() 
{
	var e = $(this.getElement());
	
	this.onStateChange = function() 
	{
		var chart1; 
		$(document).ready(function() {
		      chart1 = new Highcharts.Chart({
		         chart: {
		            renderTo: 'myJSComponent',
		            type: 'bar'
		         },
		         title: {
		            text: 'Fruit Consumption'
		         },
		         xAxis: {
		            categories: ['Apples', 'Bananas', 'Oranges']

		         },
		         yAxis: {
		            title: {
		               text: 'Fruit eaten'
		            }
		         },
		         series: [{
		            name: 'Jane',
		            data: [1, 0, 4]

		         }, {
		            name: 'John',
		            data: [5, 7, 3]

		         }]
		      });
		   });
	}
    
};

I hope someone can help me. I believe it is something due to dom rendering behavior. After reload page, everything is fine and chart is shown, but on first load highchart.js seems to be not working because it cannot find div with ID myJSComponent.

UPDATE: It also happens to multiple reloads, that highchart.js cannot find div…

Best reagrds
Steffen

Hi everyone,

after trial & error I found out the problem…


[s]
this.setId("myJSComponent");
[/s]
chart.setId("myJSComponent");

See the whole project of highchart.js integration
here

Best regards
Steffen