load html into div with javascript included - javascript

I have a site which loads html (comming from a database) into a div.
Using Backbone as a framework and Handlebars as templating tool.
In this html I also have some javascript which also works perfectly.
However, when I try to also include the plotly cdn or even the whole javascript it will not recognize Plotly. resulting into the error:
"Plotly not defined"
I tried to solve this loading Plotly using jQuery and even placing the full minified Plotly Code into the HTML however with no result.
This is html / javascript code what works when loaded into a div.:
<div class='ldbp_img' style='overflow: auto; height:100%; width: 100%;'></div>
<script type='application/javascript' language='JavaScript'>
if (!Date.now) {
Date.now = function() { return new Date().getTime(); }
}
var img = new Image(),
imageUrl = "http://new.image.nu/1234.png',
interval = 30000;
$(img).attr('width', '100%');
$(img).attr('height', '100%');
var setImg = function () {
//var img = new Image();
var time = Math.floor(Date.now() / 1000);
img.src = imageUrl + time;
$('.ldbp_img').html(img);
};
img.src = imageUrl';
$('.ldbp_img').html(img);
if (window.countInt) {
clearInterval(window.countInt);
window.countInt = null;
}
window.countInt = setInterval(setImg, interval);
</script>
When loading plotly it doesn't work:
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id='my-graph' style='overflow: auto; height:100%; width: 100%;'></div>
<script>
// Some data omitted for clarity on screen!
var data = [{
name: "Asia",
text: ["Afghanistan", "Bahrain", "Bangladesh", "Yemen, Rep."],
marker: {
sizemode: "area",
sizeref: 200000,
size: [31889923, 708573, 150448339, 22211743]
},
mode: "markers",
y: [974.5803384, 29796.04834, 1391.253792, 2280.769906],
x: [43.828, 75.635, 64.062, 62.698],
uid: "99da6d"
}, {
name: "Europe",
text: ["Albania", "Austria", "Belgium", "United Kingdom"],
marker: {
sizemode: "area",
sizeref: 200000,
size: [3600523, 8199783, 10392226, 60776238]
},
mode: "markers",
y: [5937.029526, 36126.4927, 33692.60508, 33203.26128],
x: [76.423, 79.829, 79.441, 79.425],
uid: "9d3ba4"
}, {
name: "Oceania",
text: ["Australia", "New Zealand"],
marker: {
sizemode: "area",
sizeref: 200000,
size: [20434176, 4115771]
},
mode: "markers",
y: [34435.36744, 25185.00911],
x: [81.235, 80.204],
uid: "f9fb74"
}];
var layout = {
xaxis: {
title: 'Life Expectancy'
},
yaxis: {
title: 'GDP per Capita',
type: 'log'
},
margin: {
t: 20
},
hovermode: 'closest'
};
Plotly.plot('my-graph', data, layout);
</script>
I also tried this using jQuery with no result:
<div id='my-graph' style='overflow: auto; height:100%; width: 100%;'></div>
<script>
$.ajax({
url: "https://cdn.plot.ly/plotly-latest.min.js",
dataType: "script",
cache: true,
success: function () {
runNow();
}
});
// Some data omitted for clarity on screen!
var data = [{
name: "Asia",
text: ["Afghanistan", "Bahrain", "Bangladesh", "Yemen, Rep."],
marker: {
sizemode: "area",
sizeref: 200000,
size: [31889923, 708573, 150448339, 22211743]
},
mode: "markers",
y: [974.5803384, 29796.04834, 1391.253792, 2280.769906],
x: [43.828, 75.635, 64.062, 62.698],
uid: "99da6d"
}, {
name: "Europe",
text: ["Albania", "Austria", "Belgium", "United Kingdom"],
marker: {
sizemode: "area",
sizeref: 200000,
size: [3600523, 8199783, 10392226, 60776238]
},
mode: "markers",
y: [5937.029526, 36126.4927, 33692.60508, 33203.26128],
x: [76.423, 79.829, 79.441, 79.425],
uid: "9d3ba4"
}, {
name: "Oceania",
text: ["Australia", "New Zealand"],
marker: {
sizemode: "area",
sizeref: 200000,
size: [20434176, 4115771]
},
mode: "markers",
y: [34435.36744, 25185.00911],
x: [81.235, 80.204],
uid: "f9fb74"
}];
var layout = {
xaxis: {
title: 'Life Expectancy'
},
yaxis: {
title: 'GDP per Capita',
type: 'log'
},
margin: {
t: 20
},
hovermode: 'closest'
};
var runNow = function () {
Plotly.plot('my-graph', data, layout);
};
</script>
This does work in jsfiddle, the only difference is that I do not load the html asynchronously into the DOM.
working fiddles:
https://jsfiddle.net/b2js15nm/
https://jsfiddle.net/b2js15nm/1/
Hence!: I cannot use backbone and handlebars to really re-create the situation. It looks like the AMD of Plotly does not work when loaded later on the page. Therefore Plotly will be undefined.

If you want dynamically add script into page, try to create script element and listen to load event and after that initialize your logic, e.g.:
var script = document.createElement('script');
script.setAttribute('src', 'https://cdn.plot.ly/plotly-latest.min.js');
document.body.appendChild(script);
script.addEventListener('load', function () {
// Plotly loaded
console.log(Plotly);
})

As I was thinking that the AMD module was the issue, I tried to load the script using require. I am already using require so I needn't do much to implement it.
Here is what the page looks like now:
<div id='my-graph' style='overflow: auto; height:100%; width: 100%;'></div>
<script>
require(['https://cdn.plot.ly/plotly-latest.min.js'], function (Plotly) {
// Some data omitted for clarity on screen!
var data = [{
name: "Asia",
text: ["Afghanistan", "Bahrain", "Bangladesh", "Yemen, Rep."],
marker: {
sizemode: "area",
sizeref: 200000,
size: [31889923, 708573, 150448339, 22211743]
},
mode: "markers",
y: [974.5803384, 29796.04834, 1391.253792, 2280.769906],
x: [43.828, 75.635, 64.062, 62.698],
uid: "99da6d"
}, {
name: "Europe",
text: ["Albania", "Austria", "Belgium", "United Kingdom"],
marker: {
sizemode: "area",
sizeref: 200000,
size: [3600523, 8199783, 10392226, 60776238]
},
mode: "markers",
y: [5937.029526, 36126.4927, 33692.60508, 33203.26128],
x: [76.423, 79.829, 79.441, 79.425],
uid: "9d3ba4"
}, {
name: "Oceania",
text: ["Australia", "New Zealand"],
marker: {
sizemode: "area",
sizeref: 200000,
size: [20434176, 4115771]
},
mode: "markers",
y: [34435.36744, 25185.00911],
x: [81.235, 80.204],
uid: "f9fb74"
}];
var layout = {
xaxis: {
title: 'Life Expectancy'
},
yaxis: {
title: 'GDP per Capita',
type: 'log'
},
margin: {
t: 20
},
hovermode: 'closest'
};
Plotly.plot('my-graph', data, layout);
});
</script>

Related

Last label on xaxis disappears when resize

I am trying to force highcharts to show last label on x-axis when "step" is enabled. Code below works but it hides last label when I change device width (let's say open chrome console). Problem arises on mobile devices when I scroll down after the chart, last label disappears.
chart:
{
renderTo: "container",
type: "line",
events:{
load:function(){
var ticks = $.map(this.axes[0].ticks, function(t){return t;});
ticks[ticks.length-2].render(0);
}
}
}
First of all the last label 2020 is appearing because of your logic in load event. Ideally that label shouldn't be appearing because your step value is 3. Anyways, you need to add the same logic of load in redraw event to get the last label on resize.
const df = [
{ Period: 2009, value: 1056043 },
{ Period: 2010, value: 1278495 },
{ Period: 2011, value: 1482508 },
{ Period: 2012, value: 1545703 },
{ Period: 2013, value: 1579593 },
{ Period: 2014, value: 1620531.9 },
{ Period: 2015, value: 1502572.2 },
{ Period: 2016, value: 1451010.7 },
{ Period: 2017, value: 1546273 },
{ Period: 2018, value: 1663982.3 },
{ Period: 2019, value: 1643160.9 },
{ Period: 2020, value: 1431638.4 }
];
var chart = new Highcharts.Chart({
chart: {
renderTo: "container",
height: 300,
type: "areaspline",
events: {
load: function () {
var ticks = $.map(this.axes[0].ticks, function (t) {
return t;
});
ticks[ticks.length - 2].render(0);
},
redraw: function () {
var ticks = $.map(this.axes[0].ticks, function (t) {
return t;
});
ticks[ticks.length - 2].render(0);
}
}
},
title: {
text: "Emissions of CO2 - from Fossil Fuels - Total (CDIAC)"
},
xAxis: {
categories: df.map((o) => o.Period),
labels: {
step: 3,
style: {
fontFamily: "Arial, Helvetica, sans-serif;",
fontSize: "0.8rem",
fontWeight: "600",
background: "#000000",
whiteSpace: "nowrap",
textOverflow: "none"
}
},
showLastLabel: true,
endOnTick: true,
overflow: "allow"
},
yAxis: {
min: 0
},
series: [
{
data: df.map((o) => o.value),
name: "Germany"
}
]
});

Json data for apexcharts

I have some problems rendering some data from a JSON in my apexchart series.
Here is the example of my chart with the data that I want to be in my JSON, and i don't know how to write it.
var _seed = 42;
Math.random = function() {
_seed = _seed * 16807 % 2147483647;
return (_seed - 1) / 2147483646;
};
var options = {
series: [{
name: "Q",
data: [0, 4800, 9500, null],
},
{
name: "Q - 1",
data: [0, 6500, 12000, 16000]
},{
name: "Q Target",
data: [15500, 15500, 15500, 15500]
},
],
chart: {
height: 350,
type: 'line',
zoom: {
enabled: false
}
},
dataLabels: {
enabled: false
},
stroke: {
curve: 'straight'
},
title: {
text: 'Clicks',
align: 'left'
},
grid: {
row: {
colors: ['#f3f3f3', 'transparent'], // takes an array which will be repeated on columns
opacity: 0.5
},
},
xaxis: {
categories: [' ', 'Month1', 'Month2', 'Month3'],
}
};
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
#chart {
max-width: 450px;
margin: 35px auto;
}
<script src="https://cdn.jsdelivr.net/npm/promise-polyfill#8/dist/polyfill.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/eligrey-classlist-js-polyfill"></script>
<script src="https://cdn.jsdelivr.net/npm/findindex_polyfill_mdn"></script>
<script src="https://cdn.jsdelivr.net/npm/es6-promise#4/dist/es6-promise.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/es6-promise#4/dist/es6-promise.auto.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<div id="chart"></div>
If someone could give me a hint, is kindly appreciated.
The JSON looks like this , for retrieving data for the apexchart
{
"data_clicks":[
{
"name":"Q",
"data":[
{
"x":" ",
"y":0
},
{
"x":"Month1",
"y":2400
},
{
"x":"Month2",
"y":5200
},
{
"x":"Month3",
"y":null
}
]
},
{
"name":"Q - 1",
"data":[
{
"x":" ",
"y":0
},
{
"x":"Month1",
"y":1800
},
{
"x":"Month2",
"y":7150
},
{
"x":"Month3",
"y":10200
}
]
},
{
"name":"Q Target",
"data":[
{
"x":" ",
"y":11000
},
{
"x":"Month1",
"y":11000
},
{
"x":"Month2",
"y":11000
},
{
"x":"Month3",
"y":11000
}
]
}
],

ZingChart pie tooltip not displaying

I have a pie ZingChart I'm using to show simple data. It happens to be using angular and updates the series object as the user drills down.
Everything is working fine except...the tooltip does not display? It doesn't display at any point, regardless of interaction or series assignment. The standard mouseover highlights work, and clicking nodes is fine, but no tooltip. Any ideas? Can't work out what I'm missing!
My chart config is:
{
type: "pie",
id: 'chart-1',
title: {
textAlign: 'center',
text: "Loading..."
},
"legend":{
"border-width":1,
"border-color":"gray",
"border-radius":"5px",
"marker":{
"type":"circle"
},
"toggle-action":"remove",
"icon":{
"line-color":"#9999ff"
}
},
"plot": {
"animation":{
"on-legend-toggle": true,
"effect": 5,
"method": 1,
"sequence": 1,
"speed": 0.7
},
"value-box": {
"text": "$%v",
"negation": "currency",
"thousands-separator": ",",
"font-color": "black",
"placement":"in",
"offset-r":"50%",
"font-size":"12"
},
"tooltip":{
"text":"%t: %v (%npv%)"
},
"decimals": "0",
"detach": false
},
series: [],
shapes: [{
type: 'triangle',
backgroundColor: '#66ccff',
size: 10,
angle: -90,
x: 20,
y: 20,
cursor: 'hand',
id: 'backwards'
}]
};
The - in chart-1 is causing an issue with our parse/selector process. If you change the id to chart_1 everything will work fine.
var myConfig = {
"graphset":[
{
"type":"pie",
"id":"chart_1",
"title":{
"textAlign":"center",
"text":"Loading..."
},
"legend":{
"border-width":1,
"border-color":"gray",
"border-radius":"5px",
"marker":{
"type":"circle"
},
"toggle-action":"remove",
"icon":{
"line-color":"#9999ff"
}
},
"plot":{
"animation":{
"on-legend-toggle":true,
"effect":5,
"method":1,
"sequence":1,
"speed":0.7
},
"value-box":{
"text":"$%v",
"negation":"currency",
"thousands-separator":",",
"font-color":"black",
"placement":"in",
"offset-r":"50%",
"font-size":"12"
},
"decimals":"0",
"detach":false
},
"tooltip":{
"text":"%t: %v (%npv%)"
},
"series":[
{
"values":[118],
"text":"0-30"
},
{
"values":[118],
"text":"0-30"
},
{
"values":[118],
"text":"0-30"
}
],
"shapes":[
{
"type":"triangle",
"backgroundColor":"#66ccff",
"size":10,
"angle":-90,
"x":20,
"y":20,
"cursor":"hand",
"id":"backwards"
}
]
}
]
};
zingchart.render({
id: 'myChart',
data: myConfig,
height: '100%',
width: '100%'
});
html, body {
height:100%;
width:100%;
margin:0;
padding:0;
}
#myChart {
height:100%;
width:100%;
min-height:150px;
}
<!DOCTYPE html>
<html>
<head>
<script src= "https://cdn.zingchart.com/zingchart.min.js"></script>
</head>
<body>
<div id="myChart"></div>
</body>
</html>

Unable to edit custom text items in Ext charts

I have a chart made with Ext js.The chart has some custom text items. I would like to dynamically change these texts.I want these text components as part of svg because exported images of chart should also contains these custom texts.
JSFiddle
Ext.onReady(function() {
Ext.define("PopulationPoint", {
extend: "Ext.data.Model",
fields: [ "state", "population" ]
});
var a = Ext.create("Ext.draw.Text", {
type: "text",
text: "Initial Text",
font: "24px Arial",
width: 500,
height: 100,
x: 20,
y: 20
});
var b = Ext.create("Ext.data.Store", {
model: "PopulationPoint",
data: [ {
state: "Alabama",
population: 4802740
}, {
state: "Alaska",
population: 722718
}, {
state: "Arizona",
population: 6482505
}, {
state: "Arkansas",
population: 2937979
}, {
state: "California",
population: 37691912
}, {
state: "Colorado",
population: 5116796
}, {
state: "Connecticut",
population: 3580709
}, {
state: "Delaware",
population: 907135
}, {
state: "DC",
population: 617996
} ]
});
Ext.create("Ext.chart.Chart", {
renderTo: Ext.getBody(),
width: 470,
height: 400,
store: b,
items: [ a ],
series: [ {
type: "pie",
field: "population",
label: {
field: "state",
display: "outside",
font: "12px Arial"
}
} ]
});
setInterval(function() {
a.setText("NewText"); // This statement has no use
}, 3e3);
});
Anybody knows how to fix this? Thanks in advance.
Update
It worked when I used Ext.draw.Sprite instead of Ext.draw.Text. But still exported image of chart contains the old text. Updated Jsfiddle
var txtDraw = Ext.create('Ext.draw.Sprite', {
type:'text',
text : 'Initial Text',
font : '24px Arial',
width : 500,
height: 100,
x:20,
y:20
});
txtDraw.setAttributes({ 'text':'Jeff'},true )
use setAttributes method of Ext.draw.Sprite
reference - http://docs.sencha.com/extjs/4.1.3/#!/api/Ext.draw.Sprite-method-setAttributes
I believe it is a bug because although setText method shows a sensible code:
setText: function(text) {
var me = this,
surface,
sprite;
if (me.rendered) {
surface = me.surface;
sprite = surface.items.items[0];
me.text = text || '';
surface.remove(sprite);
me.textConfig.type = 'text';
me.textConfig.text = me.text;
sprite = surface.add(me.textConfig);
sprite.setAttributes({
rotate: {
degrees: me.degrees
}
}, true);
if (me.autoSize || me.viewBox) {
me.updateLayout();
}
} else {
me.on({
render: function() {
me.setText(text);
},
single: true
});
}
}
the problem is the text sprite is never rendered, me.rendered stays false so the code is never executed. A very dirty workaround would be to set rendered flag from outside.

Ammaps - My own images need to be added in particular latitude and longitude

I have been given the following requirement.
Need to plot weather for particular main cities in Canada
I am able to get the current weather details from an API in internet through (web handler and query strings.)
Hence, I have the latitude and longitude details handy along with the the weather condition(Cloudy , sunny,Rainy etc)
I just need to show clouds on city where it is cloudy , Rainy image on city where it's raining etc
This has to be done in Javascript AMmaps .
My complete code is pasted below.I don't find a way to push my own images to the Map
AmCharts.ready(function () {
map = new AmCharts.AmMap();
map.pathToImages = "http://www.amcharts.com/lib/3/images/";
map.panEventsEnabled = true;
map.backgroundColor = "#666666";
map.backgroundAlpha = 1;
colorSteps: 1,
map.zoomControl.panControlEnabled = true;
map.zoomControl.zoomControlEnabled = true;
var dataProvider = {
map: "canadaLow",
getAreasFromMap: true,
areas: [{
id: "CA-AB", value: 3645257
},
{
id: "CA-BC", value: 4400057
},
{
id: "CA-MB", value: 1208268
},
{
id: "CA-NB", value: 751171
},
{
id: "CA-NL", value: 514536
},
{
id: "CA-NS", value: 921727
},
{
id: "CA-NT", value: 41462
},
{
id: "CA-NU", value: 31906
},
{
id: "CA-ON", value: 12851821
},
{
id: "CA-PE", value: 140204
},
{
id: "CA-QC", value: 7903001
},
{
id: "CA-SK", value: 1033381
},
{
id: "CA-YT", value: 33897
}],
images: [{ latitude: 45.532, longitude: -73.79, balloonText: "T3695", type: "circle", scale: 0.3 },
{ latitude: 43.7143, longitude: -79.7235, balloonText: "T3623", type: "circle", scale: 0.3 },
{ latitude: 45.5925, longitude: -73.5418, balloonText: "T3705", type: "circle", scale: 0.3 },
{ latitude: 43.4136, longitude: -79.7052, balloonText: "T3670", type: "circle", scale: 0.3 },
{ latitude: 51.0195, longitude: -114.1716, balloonText: "T3754", type: "circle", scale: 0.3 },
{ latitude: 45.7922, longitude: -74.0177, balloonText: "T3657", type: "circle", scale: 0.3 },
{ latitude: 42.3974, longitude: -82.2122, balloonText: "T3533", type: "circle", scale: 0.3 }],
// zoomLevel: 3.37137, // insert the values...
//zoomLatitude: 52.124368, // from the alert box...
//zoomLongitude: -96.251201,// here
};
map.dataProvider = dataProvider;
map.objectList = {
container: "listdiv"
};
map.areasSettings = {
autoZoom: false,
color: "#CDCDCD",
colorSolid: "#5EB7DE",
//selectedColor: "#5EB7DE",
//outlineColor: "#666666",
//rollOverColor: "#88CAE7",
//rollOverOutlineColor: "#FFFFFF",
selectable: true
};
map.ZoomControl = { buttonFillColor: '#CCCCCC' };
map.areasSettings = {
autoZoom: true,
//This is the parameter to be modified to change the Color of the state when SELECTED
selectedColor: "#cc9900",
//This is the parameter to be modified to change the Color of the MAP
color: '#CCFF00',
//This is the parameter to be modified to change the Color of the state when ROLLING OVER
rollOverColor: '#009900',
rollOverOutlineColor: '#009900'
};
map.mouseWheelZoomEnabled = true;
map.write("mapdiv");
});
The solution for your request in the tip section on the amchart web site.
http://www.amcharts.com/tips/weather-map/
I copy here part of the code. The key is creating an images array and the imageURL element.
var map = AmCharts.makeChart("chartdiv", {
type: "map",
"theme": "none",
pathToImages: "http://www.amcharts.com/lib/3/images/",
dataProvider: {
map: "worldLow",
zoomLevel: 5.5,
zoomLongitude: 10,
zoomLatitude: 52,
images: [{
latitude: 40.416775,
longitude: -3.703790,
imageURL: "http://extra.amcharts.com/images/weather/weather-rain.png",
width: 32,
height: 32,
label: "Madrid: +22C"
}, {
latitude: 48.856614,
longitude: 2.352222,
imageURL: "http://extra.amcharts.com/images/weather/weather-storm.png",
width: 32,
height: 32,
label: "Paris: +18C"
},#### More cities
{
latitude: 59.329323,
longitude: 18.068581,
imageURL: "http://extra.amcharts.com/images/weather/weather-rain.png",
width: 32,
height: 32,
label: "Stockholm: +8C"
}]
},
imagesSettings: {
labelRollOverColor: "#000",
labelPosition: "bottom"
},
areasSettings: {
rollOverOutlineColor: "#FFFFFF",
rollOverColor: "#CC0000",
alpha:0.8
}
});
The corresponding HTML code would be:
<script type="text/javascript" src="http://www.amcharts.com/lib/3/ammap.js"></script>
<script type="text/javascript" src="http://www.amcharts.com/lib/3/maps/js/worldLow.js"></script>
<script type="text/javascript" src="http://www.amcharts.com/lib/3/themes/none.js"></script>
<div id="chartdiv"></div>

Categories

Resources