How to render Highcharts graph into user-selected DIV - javascript

I have multiple buttons, representing webservices in form of maps and Highcharts graphs, which the user can drag into one of several containers (DIVs) on the page, in which these webservices are then displayed.
It works fine for the map/image-webservices. But it is not clear to me how to make it possible with the Highcharts graphs. I guess I have to indicate somewhere a chart.renderTo("DIVx"), but not sure about that process.
I have setup a fiddle here. For the moment, the graph is being displayed in the DIV "container". But this should disappear, and once the user drags the button "Graph :: XXX" into one of the DIVs, the graph should display there.
The HTML part:
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<!-- this container should disappear -->
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
<!-- buttons -->
<div id="map_npp" draggable="true" ondragend="onDragEnd(event)" ondragstart="onDragStart(event)" style="float: left">
<h4 style="float: left">Map :: NPP</h4>
</div>
<div id="map_precipitations" draggable="true" ondragend="onDragEnd(event)" ondragstart="onDragStart(event)" style="float: left">
<h4 style="float: left">Map :: Precipitations</h4>
</div>
<div id="map_temperature" draggable="true" ondragend="onDragEnd(event)" ondragstart="onDragStart(event)" style="float: left">
<h4 style="float: left">Map :: Temperature</h4>
</div>
<div id="graph_gdp" draggable="true" ondragend="onDragEnd(event)" ondragstart="onDragStart(event)" style="float: left">
<h4 style="float: left">Graph :: GDP</h4>
</div>
<div id="graph_xxx" draggable="true" ondragend="onDragEnd(event)" ondragstart="onDragStart(event)" style="float: left">
<h4 style="float: left">Graph :: XXX</h4>
</div>
<br clear="all" />
<!-- dropzone DIVs -->
<div id="dropzone1" class="static dropzone" ondrop="onDrop(event)" ondragover="onDragOver(event)" ondragleave="onDragLeave(event)"></div>
<div id="dropzone2" class="static dropzone" ondrop="onDrop(event)" ondragover="onDragOver(event)" ondragleave="onDragLeave(event)"></div>
<div id="dropzone3" class="static dropzone" ondrop="onDrop(event)" ondragover="onDragOver(event)" ondragleave="onDragLeave(event)"></div>
<div id="dropzone4" class="static dropzone" ondrop="onDrop(event)" ondragover="onDragOver(event)" ondragleave="onDragLeave(event)"></div>
The javascript/jquery part for the graph:
var csv = "2010/01/01,51.67074582499006,13.789093928493081,-0.0010074468085106377\n" +
"2010/02/01,51.67074582499006,13.789093928493081,0.0024117021276595747\n" +
"2010/03/01,51.67074582499006,13.789093928493081,0.026550000000000004\n" +
"2010/04/01,51.67074582499006,13.789093928493081,0.08252659574468087\n" +
"2010/05/01,51.67074582499006,13.789093928493081,0.12837446808510639\n" +
"2010/06/01,51.67074582499006,13.789093928493081,0.140618085106383\n" +
"2010/07/01,51.67074582499006,13.789093928493081,0.0668787234042553\n" +
"2010/08/01,51.67074582499006,13.789093928493081,0.10335744680851064\n" +
"2010/09/01,51.67074582499006,13.789093928493081,0.08095000000000001\n" +
"2010/10/01,51.67074582499006,13.789093928493081,0.0400159574468085\n" +
"2010/11/01,51.67074582499006,13.789093928493081,0.004214893617021277\n" +
"2010/12/01,51.67074582499006,13.789093928493081,-0.0018680851063829788\n" +
"2011/01/01,51.67074582499006,13.789093928493081,0.0011914893617021279\n" +
"2011/02/01,51.67074582499006,13.789093928493081,0.003752127659574468\n" +
"2011/03/01,51.67074582499006,13.789093928493081,0.027225531914893623"
function extract(csv) {
var rows = csv.split(/\r\n|\n/);
var data;
var series = [];
var serie = {
name: -1,
data: []
};
for (var i = 0; i < rows.length; i++) {
data = rows[i].split(',');
if (serie.name === -1) {
serie.name = data[0].substr(0, 4);
} else {
if (serie.name !== data[0].substr(0, 4)) {
series.push(serie);
serie = {
name: data[0].substr(0, 4),
data: []
};
}
}
serie.data.push(parseFloat(data[3]));
}
series.push(serie);
return series;
}
$(function() {
Highcharts.chart('container', {
title: {
text: 'Monthly Average Temperature',
x: -20 //center
},
subtitle: {
text: 'Source: WorldClimate.com',
x: -20
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
]
},
yAxis: {
title: {
text: 'Temperature (°C)'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: '°C'
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: extract(csv),
});
});
The javascript/jquery part for the draggable buttons and target DIVs:
//just to know which button is being dragged we will use this variable
var draggingDiv;
function onDragOver(e) {
e.preventDefault();
e.target.classList.add("over-me");
}
function onDragLeave(e) {
e.target.classList.add("static");
e.target.classList.remove("over-me");
}
function onDragStart(e) {
draggingDiv = e.target;
e.target.innerHTML = "<h4>You are Dragging me</h4>";
}
function onDragEnd(e) {
e.target.innerHTML = "<h4>Drag Me into the Box :)</h4>";
e.target.parentElement.classList.add("static");
draggingDiv.innerHTML = "<h4>Dragged once Can't drag me now:)</h4>";
// e.target.innerHTML = "<h4>You Dropped Me In "+e.target.parentElement.id+"</h4>";
}
function onDrop(e) {
e.preventDefault();
e.target.classList.remove("over-me");
//uncommment the below line if want that the button should not be draggable once it has been dropped in a div already
//draggingDiv.draggable=false;
//e.target.appendChild(draggingDiv);/commented as this will take the button to the div but we want it to at the original pposition
//e.target.innerHTML="<span>Please Change My innerHTML or call some function that loads data That handles the graph/map creation in this Div</span>";
if (draggingDiv.id == "map_npp") {
e.target.innerHTML = "<img style='margin-top: 0' src='http://npp.unepgrid.ch/images/wms_fake.png'>";
} else if (draggingDiv.id == "map_precipitations") {
e.target.innerHTML = "<img style='margin-top: 0' src='http://npp.unepgrid.ch/images/wms_fake.png'>";
} else if (draggingDiv.id == "map_temperature") {
e.target.innerHTML = "<img style='margin-top: 0' src='http://npp.unepgrid.ch/images/wms_fake.png'>";
} else if (draggingDiv.id == "graph_gdp") {
e.target.innerHTML = "<img style='margin-top: 0' src='http://npp.unepgrid.ch/images/wms_fake.png'>";
} else if (draggingDiv.id == "graph_xxx") {
e.target.innerHTML = "<img style='margin-top: 0' src='http://npp.unepgrid.ch/images/wms_fake.png'>";
}
}
Thanks for any hints how this could be implemented.

You need to render the chart onDrop event. The container for the chart will be the target of that event. An element in which the chart will be rendered can be set via chart.renderTo property or as a parameter in the chart constructing function - see API.
The example can be found below. I also destroy the previous chart before a new one is created.
var chart;
function onDrop(e) {
e.preventDefault();
e.target.classList.remove("over-me");
if (chart) {
chart.destroy();
}
var options = {
chart: {},
series: [{
data: [1,2,3,4,5]
}]
};
if (draggingDiv.id == "map_npp") {
} else if (draggingDiv.id == "map_precipitations") {
options.chart.type = 'column';
} else if (draggingDiv.id == "map_temperature") {
} else if (draggingDiv.id == "graph_gdp") {
options.series.data = [5,4,3,2,1];
} else if (draggingDiv.id == "graph_xxx") {
options.series.data = [5,4,3,2,1];
options.chart.type = 'column';
}
chart = Highcharts.chart(e.target, options);
}
example: https://jsfiddle.net/1nye1zk7/

Related

Can't display another Highcharts chart on my HTML page - Django

Been looking at Highcharts doc and also "Integrating Django and Highcharts" by simpleisbetterthancomplex. I'm not sure what went wrong with my codes, that the second charts ain't display. I'm using Django views.py to retrieve data from the database.
def dashboard_viewUser(request):
dataset = Profile.objects\
.values('is_active')\
.annotate(is_active_count = Count('is_active', filter = Q(is_active = True)),
not_is_active_count = Count('is_active', filter = Q(is_active = False)))\
.order_by('is_active')
categories = list()
is_active_series_data = list()
not_is_active_series_data = list()
for entry in dataset:
categories.append('%s Active' % entry['is_active'])
is_active_series_data.append(entry['is_active_count'])
not_is_active_series_data.append(entry['not_is_active_count'])
is_active_series = {
'name': 'Active user',
'data': is_active_series_data,
'color': 'green'
}
not_is_active_series = {
'name': 'Inactive user',
'data': not_is_active_series_data,
'color': 'red'
}
chart = {
'chart': {
'type': 'column'
},
'title': {
'text': 'Active user on Current Platform'
},
'xAxis': {
'categories': categories
},
'yAxis': {
'title': {
'text': 'No.of users'
},
'tickInterval': 1
},
'plotOptions': {
'column': {
'pointPadding': 0.2,
'borderWidth': 0
}
},
'series': [is_active_series, not_is_active_series]
}
dump = json.dumps(chart)
return render(request, 'accounts/dashboard.html', {
'chart': dump
})
`
def dashboard_viewDepartment(request):
dataset = Department.objects \
.values('department') \
.annotate(IT_count=Count('department', filter=Q(department="IT")),
Sales_count=Count('department', filter=Q(department="Sales")),
Admin_count=Count('department', filter=Q(department="Admin")),
HR_count=Count('department', filter=Q(department="HR")),) \
.order_by('department')
categories = list()
IT_series_data = list()
Sales_series_data = list()
Admin_series_data = list()
HR_series_data = list()
for entry in dataset:
categories.append('%s Department' % entry['department'])
IT_series_data.append(entry['IT_count'])
Sales_series_data.append(entry['Sales_count'])
Admin_series_data.append(entry['Admin_count'])
HR_series_data.append(entry['HR_count'])
IT_series = {
'name': 'IT',
'data': IT_series_data,
'color': 'green'
}
Sales_series = {
'name': 'Sales',
'data': Sales_series_data,
'color': 'yellow'
}
Admin_series = {
'name': 'Admin',
'data': Admin_series_data,
'color': 'red'
}
HR_series = {
'name': 'HR',
'data': HR_series_data,
'color': 'blue'
}
chart2 = {
'chart': {'type': 'column'},
'title': {'text': 'Containers per department'},
'xAxis': {'categories': categories},
'yAxis': {
'title': {
'text': 'No.of containers'},
'tickInterval': 1
},
'plotOptions': {
'column': {
'pointPadding': 0.2,
'borderWidth': 0
}
},
'series': [IT_series, Sales_series, Admin_series, HR_series]
}
dump = json.dumps(chart2)
return render(request, 'accounts/dashboard.html', {'chart2': dump})
<div class="carousel-inner">
<div class="carousel-item active">
<div class="border" id="container" style="min-width: 100px; height:
400px; margin: 0 auto;"></div>
<script src="https://code.highcharts.com/highcharts.src.js">
</script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
Highcharts.chart('container', {
{
chart | safe
}
});
</script>
</div>
<div class="carousel-item">
<div class="border" id="container2" style="min-width: 100px;
height: 400px; margin: 0 auto;"></div>
<script src="https://code.highcharts.com/highcharts.src.js">
</script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js">
</script>
<script>
Highcharts.chart('container2', {
{
chart2 | safe
}
});
</script>
</div>
<div class="carousel-item">
<div class="carousel-caption">
<h3>Currently Unavailable</h3>
</div>
</div>
</div>
Expected two charts to be display on two different panel of the carousel
Actually You just need one script src of the highchart and jquery.min.js .
Change chart2 to chart.
<script src="https://code.highcharts.com/highcharts.src.js">
</script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
<div class="carousel-inner">
<div class="carousel-item active">
<div class="border" id="container" style="min-width: 100px; height:
400px; margin: 0 auto;"></div>
Highcharts.chart('container', {{ chart|safe }});
</script>
</div>
<div class="carousel-item">
<div class="border" id="container2" style="min-width: 100px;
height: 400px; margin: 0 auto;"></div>
<script>
Highcharts.chart('container2', {{ chart|safe }});
</script>
</div>
<div class="carousel-item">
<div class="carousel-caption" >
<h3>Currently Unavailable</h3>
</div>
</div>
</div>
You don't need multiple jquery/highchart. Just include it once at top of the page and it would work fine for multiple charts. I've updated your code a bit and since I don't have access to your data output from safe method, I've initialised the chart as a blank one.
<!-- Place your javascripts once -->
<script src="https://code.highcharts.com/highcharts.src.js">
</script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<div class="carousel-inner">
<div class="carousel-item active">
<div class="border" id="container" style="min-width: 100px; height:
400px; margin: 0 auto;"></div>
<script>
Highcharts.chart('container', {
title: {
text: 'Im Chart 1' // Replace your {{ chart|safe }} here.
},
});
</script>
</div>
<div class="carousel-item">
<div class="border" id="container2" style="min-width: 100px;
height: 400px; margin: 0 auto;"></div>
<script>
Highcharts.chart('container2', {
title: {
text: 'Im Chart 2' //Replace your {{ chart2|safe }} here.
},
});
</script>
</div>
<div class="carousel-item">
<div class="carousel-caption">
<h3>Currently Unavailable</h3>
</div>
</div>
</div>
Check out this fiddle for a working output.
https://jsfiddle.net/ebkr65ma/

How to navigate to next object in javascript

https://codepen.io/abhilashn/pen/BRepQz
// JavaScript Document
var quiz = { "JS" : [
{
"id" : 1,
"question" : "Inside which HTML element do we put the JavaScript?",
"options" : [
{"a": "<script>", "b":"<javascript>", "c":"<scripting>", "d":"<js>"}
],
"answer":"<script>",
},
{
"id" : 2,
"question" : "What is the correct JavaScript syntax to change the content of the HTML element below.",
"options" : [
{"a": "document.getElementById('demo').innerHTML = 'Hello World!';",
"b":"document.getElementByName('p').innerHTML = 'Hello World!';",
"c":"document.getElement('p').innerHTML = 'Hello World!';",
"d":"#demo.innerHTML = 'Hello World!';"}
],
"answer":"a",
}
]
}
var score = 0;
var qno = 1;
var currentque = 0;
var totalque = quiz.JS.length;
displayQuiz = function(cque) {
currentque = cque;
$("#qid").html(this.qno);
//console.log(quiz.JS[currentque].options[0]);
$("#question").html(quiz.JS[currentque].question);
for (var key in quiz.JS[currentque].options[0]) {
if (quiz.JS[currentque].options[0].hasOwnProperty(key)) {
console.log(key + " -> " + quiz.JS[currentque].options[0][key]);
$("#question-options").append(
"<div class='form-check option-block'>" +
"<label class='form-check-label'>" +
"<input type='radio' class='form-check-input' name='option' id='q"+key+"' value='" + quiz.JS[currentque].options[0][key] + "'>" +
quiz.JS[currentque].options[0][key] +
"</label>"
);
}
}
}
checkAnswer = function(option) {
var answer = quiz.JS[currentque].answer;
option = option.replace(/\</g,"<") //for <
option = option.replace(/\>/g,">") //for >
if(option == quiz.JS[currentque].answer) {
score = score + 1;
}
}
changeQuestion = function(cque) {
currentque = currentque + cque;
displayQuiz(currentque);
}
$(document).ready(function() {
displayQuiz(0);
});
$('input[type=radio][name=option]').change(function() {
if (this.checked) {
checkAnswer(value);
}
});
$('#next').click(function() {
changeQuestion(1);
});
You need to modify your solution with these changes:
1) To update the question number when you click next
$("#qid").html(this.qno++);//<--Update question number
2) You need to clear the div so that next question's options could be shown. Just appending would keep on adding the options.
$("#question").html(quiz.JS[currentque].question);
$("#question-options").html("");//<--Clear previous question
3) Modify next button's click handler as shown below:
$('#next').click(function(e) {
e.preventDefault();
var quiz = {
"JS": [{
"id": 1,
"question": "Inside which HTML element do we put the JavaScript?",
"options": [{
"a": "<script>",
"b": "<javascript>",
"c": "<scripting>",
"d": "<js>"
}],
"answer": "<script>",
},
{
"id": 2,
"question": "What is the correct JavaScript syntax to change the content of the HTML element below.",
"options": [{
"a": "document.getElementById('demo').innerHTML = 'Hello World!';",
"b": "document.getElementByName('p').innerHTML = 'Hello World!';",
"c": "document.getElement('p').innerHTML = 'Hello World!';",
"d": "#demo.innerHTML = 'Hello World!';"
}],
"answer": "a",
}
]
}
var score = 0;
var qno = 1;
var currentque = 0;
var totalque = quiz.JS.length;
displayQuiz = function(cque) {
currentque = cque;
$("#qid").html(this.qno++);//<--Update question number
//console.log(quiz.JS[currentque].options[0]);
$("#question").html(quiz.JS[currentque].question);
$("#question-options").html("");//<--Clear previous question
for (var key in quiz.JS[currentque].options[0]) {
if (quiz.JS[currentque].options[0].hasOwnProperty(key)) {
$("#question-options").append(
"<div class='form-check option-block'>" +
"<label class='form-check-label'>" +
"<input type='radio' class='form-check-input' name='option' id='q" + key + "' value='" + quiz.JS[currentque].options[0][key] + "'>" +
quiz.JS[currentque].options[0][key] +
"</label>"
);
}
}
}
checkAnswer = function(option) {
var answer = quiz.JS[currentque].answer;
option = option.replace(/\</g, "<") //for <
option = option.replace(/\>/g, ">") //for >
if (option == quiz.JS[currentque].answer) {
score = score + 1;
}
}
changeQuestion = function(cque) {
currentque = currentque + cque;
displayQuiz(currentque);
}
$(document).ready(function() {
displayQuiz(0);
});
$('input[type=radio][name=option]').change(function() {
if (this.checked) {
checkAnswer(value);
}
});
$('#next').click(function(e) {
e.preventDefault();
changeQuestion(1);
});
.content {
margin-top: 54px;
}
.quiz-body {
margin-top: 50px;
padding-bottom: 50px;
}
.option-block-container {
margin-top: 20px;
}
.option-block {
padding: 10px;
background: aliceblue;
border: 1px solid #84c5fe;
margin-bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="navbar navbar-toggleable-md navbar-inverse fixed-top bg-primary">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#">JS Quiz</a>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="nav navbar-nav mr-auto"></ul>
</div>
</nav>
<div class="content">
<div class="container-fluid">
<div class="row">
<div class="col-sm-8">
<div class="quiz-body">
<form name="quizForm">
<fieldset class="form-group">
<h4><span id="qid">1.</span> <span id="question"></span></h4>
<div class="option-block-container" id="question-options">
</div>
<!-- End of option block -->
</fieldset>
<button name="next" id="next" class="btn btn-success">Next</button>
</form>
</div>
</div>
<!-- End of col-sm-8 -->
<div class="col-sm-4">
</div>
</div>
<!-- End of row -->
</div>
<!-- ENd of container fluid -->
</div>
<!-- End of content -->

Dygraphs - synchronous zooming

I'm trying to render >3 graphs, using Dygraphs in JS.
Using some example codes, I was able to create a dummy for my work, just like this.
The demo works as it should, but here is my scenario:
I am trying to render 3 or more graphs with values from different ranges. I want to zoom in a time peroid on a graph and I want all the other graphs to zoom with it.
Right now, said graph will be zoomed and the others are going to be messed up:
$(document).ready(function() {
var someData = [
"2009/01/01,10,11,12\n" +
"2009/01/02,12,10,11\n" +
"2009/01/03,9,10,13\n" +
"2009/01/04,5,20,15\n" +
"2009/01/05,8,3,12\n",
"2009/01/01,510,511,512\n" +
"2009/01/02,518,510,511\n" +
"2009/01/03,519,510,513\n" +
"2009/01/04,525,520,515\n" +
"2009/01/05,508,513,512\n",
"2009/01/01,0.10,0.11,0.01\n" +
"2009/01/02,0.12,1,0.11\n" +
"2009/01/03,0.09,0.10,0.13\n" +
"2009/01/04,0.05,0.20,0.15\n" +
"2009/01/05,0.08,0.03,0.12\n",
"2009/01/01,110,111,112\n" +
"2009/01/02,112,110,111\n" +
"2009/01/03,109,110,113\n" +
"2009/01/04,105,120,115\n" +
"2009/01/05,108,103,112\n"
];
var graphs = ["x", "foo", "bar", "baz"];
var titles = ['', '', '', ''];
var gs = [];
var blockRedraw = false;
for (var i = 1; i <= 4; i++) {
gs.push(
new Dygraph(
document.getElementById("div" + i),
someData[i - 1], {
labels: graphs,
title: titles[i - 1],
legend: 'always'
}
)
);
}
var sync = Dygraph.synchronize(gs);
function update() {
var zoom = document.getElementById('chk-zoom').checked;
var selection = document.getElementById('chk-selection').checked;
sync.detach();
sync = Dygraph.synchronize(gs, {
zoom: zoom,
selection: selection
});
}
$('#chk-zoom, #chk-selection').change(update);
});
.chart {
width: 500px;
height: 300px;
}
.chart-container {
overflow: hidden;
}
#div1 {
float: left;
}
#div2 {
float: left;
}
#div3 {
float: left;
clear: left;
}
#div4 {
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://dygraphs.com/dygraph.js"></script>
<script src="http://dygraphs.com/src/extras/synchronizer.js"></script>
<p>Zooming and panning on any of the charts will zoom and pan all the others. Selecting points on one will select points on the others.</p>
<p>To use this, source <code>extras/synchronizer.js</code> on your page. See the comments in that file for usage.</p>
<div class="chart-container">
<div id="div1" class="chart"></div>
<div id="div2" class="chart"></div>
<div id="div3" class="chart"></div>
<div id="div4" class="chart"></div>
</div>
<p>
Synchronize what?
<input id="chk-zoom" checked="" type="checkbox">
<label for="chk-zoom">Zoom</label>
<input id="chk-selection" checked="" type="checkbox">
<label for="chk-selection">Selection</label>
</p>
For me it looks like that, the other graphs want to show the same value range for the selected time peroid. If this is the case, then do I just need to redraw the other graphs somehow?
Below, I have modified your code (only 2 lines) and now I think it is working as you need.
Inside the synchronize options, I have added the option "range" set to false. With this option, the y-axis is not synchronized, which is what you need.
The other thing I´ve done, is to force a call to update() after the graphs synchronization. In the way you had the code, the update was not called until a checkbox was modified, so at the first, the graphs synchronization was not working.
I hope this could help you and sorry for not answering before ;)
$(document).ready(function() {
var someData = [
"2009/01/01,10,11,12\n" +
"2009/01/02,12,10,11\n" +
"2009/01/03,9,10,13\n" +
"2009/01/04,5,20,15\n" +
"2009/01/05,8,3,12\n",
"2009/01/01,510,511,512\n" +
"2009/01/02,518,510,511\n" +
"2009/01/03,519,510,513\n" +
"2009/01/04,525,520,515\n" +
"2009/01/05,508,513,512\n",
"2009/01/01,0.10,0.11,0.01\n" +
"2009/01/02,0.12,1,0.11\n" +
"2009/01/03,0.09,0.10,0.13\n" +
"2009/01/04,0.05,0.20,0.15\n" +
"2009/01/05,0.08,0.03,0.12\n",
"2009/01/01,110,111,112\n" +
"2009/01/02,112,110,111\n" +
"2009/01/03,109,110,113\n" +
"2009/01/04,105,120,115\n" +
"2009/01/05,108,103,112\n"
];
var graphs = ["x", "foo", "bar", "baz"];
var titles = ['', '', '', ''];
var gs = [];
var blockRedraw = false;
for (var i = 1; i <= 4; i++) {
gs.push(
new Dygraph(
document.getElementById("div" + i),
someData[i - 1], {
labels: graphs,
title: titles[i - 1],
legend: 'always'
}
)
);
}
var sync = Dygraph.synchronize(gs);
update();
function update() {
var zoom = document.getElementById('chk-zoom').checked;
var selection = document.getElementById('chk-selection').checked;
sync.detach();
sync = Dygraph.synchronize(gs, {
zoom: zoom,
range: false,
selection: selection
});
}
$('#chk-zoom, #chk-selection').change(update);
});
.chart {
width: 500px;
height: 300px;
}
.chart-container {
overflow: hidden;
}
#div1 {
float: left;
}
#div2 {
float: left;
}
#div3 {
float: left;
clear: left;
}
#div4 {
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://dygraphs.com/dygraph.js"></script>
<script src="http://dygraphs.com/src/extras/synchronizer.js"></script>
<p>Zooming and panning on any of the charts will zoom and pan all the others. Selecting points on one will select points on the others.</p>
<p>To use this, source <code>extras/synchronizer.js</code> on your page. See the comments in that file for usage.</p>
<div class="chart-container">
<div id="div1" class="chart"></div>
<div id="div2" class="chart"></div>
<div id="div3" class="chart"></div>
<div id="div4" class="chart"></div>
</div>
<p>
Synchronize what?
<input id="chk-zoom" checked="" type="checkbox">
<label for="chk-zoom">Zoom</label>
<input id="chk-selection" checked="" type="checkbox">
<label for="chk-selection">Selection</label>
</p>

intergrating sliders in nvd3 barcharts

Ive managed to update the first few bars to have values changed manually by sliders on a normal javascript barchart.
http://jsfiddle.net/ZmnWq/68/
HTML
<div style="margin: 20px 0px 0px 60px">
<form oninput="output1.value=slider1.value">
<input type="range" name="slider1" id="slider1"/>
<output name="output1" for="slider1"></output>
</form>
<form oninput="output2.value=slider2.value">
<input type="range" name="slider2" id="slider2"/>
<output name="output2" for="slider2"></output>
</form>
<button id="updater">Update</button>
</div>
JavaScript
$(document).ready(function() {
var chartColumn = new Highcharts.Chart({
chart: {
renderTo: 'chart-column',
type: 'column',
backgroundColor: null
},
title: {
text: 'Percentage of rainfall'
},
xAxis: {
categories: [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
]
},
credits: {
enabled: false
},
yAxis: {
max: 100,
min: 0,
title: {
text: 'Rainfall (mm)'
}
},
legend: {
enabled: false,
layout: 'vertical',
backgroundColor: '#FFFFFF',
align: 'left',
verticalAlign: 'top',
x: 100,
y: 70,
floating: true,
shadow: true
},
tooltip: {
formatter: function() {
return ''+
this.x +': '+ this.y +' mm';
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Air Consumption',
data: [42, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8, 51.1]
}]
});
var $slider = $("#updater");
$slider.bind('click', function(e) {
e.preventDefault();
chartColumn.series[0].data[0].update(parseInt($("#slider1").val()));
chartColumn.series[0].data[1].update(parseInt($("#slider2").val()));
});
});
CSS
body { font-family: Arial, Helvetica, sans-serif; font-size: 12px; }
input[type="range"] {
-webkit-appearance: none;
background-color: rgb(144, 144, 144);
height: 3px;
}
input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
width: 11px;
height: 15px;
border:solid black 1px;
background:#ffffff;
-webkit-border-radius: 4px;
}
But i want to be able to make a better looking graph provided by nvd3
What i've managed to do is change an example to this
http://jsfiddle.net/0zsdmpd2/7/
HTML
<div id="chart">
<svg></svg>
</div>
</div>
<form oninput="output1.value=slider1.value">
<input type="range" name="slider1" id="slider1" />
<output name="output1" for="slider1"></output>
</form>
<form oninput="output2.value=slider2.value">
<input type="range" name="slider2" id="slider2" />
<output name="output2" for="slider2"></output>
</form>
<button id="updater">Update</button>
</div>
JavaScript
var data = [
[{
"key": "Previous","values":
[
['Resistance', 41.27, 0],
['fuel consumed', 47.96, 1],
['fuel cost', 44.65, 2]
]
}, {
"key": "Current","values":
[
['Resistance', 40.48, 0],
['fuel consumed', 45.82, 1],
['fuel cost', 40.16, 2]
]
}]
];
var n = 0;
nv.addGraph(function () {
var chart = nv.models.multiBarChart()
.x(function (d) {
return d[0];
})
.y(function (d) {
return d[1];
})
.color(['#84c1ea', '#1f77b4'])
.forceY([0, 100])
.reduceXTicks(false)
.stacked(false)
.showControls(false)
.margin({
left: 50,
right: 30
});
chart.xAxis.showMaxMin(true)
.tickFormat['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'];
chart.yAxis.tickFormat['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'];
d3.select("#chart svg")
.datum(data[n])
.transition().duration(500).call(chart);
var $slider = $("#updater");
$slider.bind('click', function(e) {
e.preventDefault();
chartColumn.Previous[0].values[0].update(parseInt($("#slider1").val()));
chartColumn.Previous[0].values[1].update(parseInt($("#slider2").val()));
});
});
Css
#chart svg {
height: 400px;
}
However, I have no idea how to use the slider to manually update the values in the graph inside the nvd3 barchart. The update button not updating the values.
Any help is deeply appreciated, as i am new to html and javascript coding, but trying to do my best to complete a job given to me.
(updated nvd3 jsfiddle graph)

getting error a.ownerDocument.defaultView is null

I am using jqxwidget. While integrating the widgets I have used jqxgrid , jqxwindow and jqxtabs
When I implement the jqxtabs I face the javascript error a.ownerDocument.defaultView
and my editor stops working.
How can I solve this issue?
I have added following code:
var initWidgets = function (tab) {
switch (tab) {
case 0:
initGrid();
break;
}
}
$('#jqxTabs').jqxTabs({ width: 'auto', height: 'auto'});
I have added my code to submit my form inside the function initGrid.
Have you tried to init the widgets within the jQWidgets Tabs initTabContent function? Example: jQWidgets Tabs Integration with UI Widgets
<!DOCTYPE html>
<html lang="en">
<head>
<title id='Description'>This demo shows how to integrate jqxTabs with other widgets.
</title>
<link rel="stylesheet" href="../../jqwidgets/styles/jqx.base.css" type="text/css" />
<script type="text/javascript" src="../../scripts/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="../../scripts/demos.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxcore.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxtabs.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxcheckbox.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxmenu.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxgrid.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxgrid.selection.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxbuttons.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxscrollbar.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxlistbox.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxdropdownlist.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxdata.js"></script>
<script type="text/javascript" src="../../jqwidgets/jqxchart.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var initGrid = function () {
var source =
{
datatype: "csv",
datafields: [
{ name: 'Date' },
{ name: 'S&P 500' },
{ name: 'NASDAQ' }
],
url: '../sampledata/nasdaq_vs_sp500.txt'
};
var dataAdapter = new $.jqx.dataAdapter(source, { async: false, loadError: function (xhr, status, error) { alert('Error loading "' + source.url + '" : ' + error); } });
$("#jqxGrid").jqxGrid(
{
width: '100%',
height: '84%',
source: dataAdapter,
columns: [
{ text: 'Date', datafield: 'Date', cellsformat: 'd', width: 250 },
{ text: 'S&P 500', datafield: 'S&P 500', width: 150 },
{ text: 'NASDAQ', datafield: 'NASDAQ' }
]
});
}
var initChart = function () {
// prepare the data
var source =
{
datatype: "csv",
datafields: [
{ name: 'Date' },
{ name: 'S&P 500' },
{ name: 'NASDAQ' }
],
url: '../sampledata/nasdaq_vs_sp500.txt'
};
var dataAdapter = new $.jqx.dataAdapter(source, { async: false, autoBind: true, loadError: function (xhr, status, error) { alert('Error loading "' + source.url + '" : ' + error); } });
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
// prepare jqxChart settings
var settings = {
title: "U.S. Stock Market Index Performance (2011)",
description: "NASDAQ Composite compared to S&P 500",
enableAnimations: true,
showLegend: true,
padding: { left: 10, top: 5, right: 10, bottom: 5 },
titlePadding: { left: 90, top: 0, right: 0, bottom: 10 },
source: dataAdapter,
categoryAxis:
{
dataField: 'Date',
formatFunction: function (value) {
return months[value.getMonth()];
},
toolTipFormatFunction: function (value) {
return value.getDate() + '-' + months[value.getMonth()];
},
type: 'date',
baseUnit: 'month',
showTickMarks: true,
tickMarksInterval: 1,
tickMarksColor: '#888888',
unitInterval: 1,
showGridLines: true,
gridLinesInterval: 3,
gridLinesColor: '#888888',
valuesOnTicks: false
},
colorScheme: 'scheme04',
seriesGroups:
[
{
type: 'line',
valueAxis:
{
displayValueAxis: true,
description: 'Daily Closing Price',
axisSize: 'auto',
tickMarksColor: '#888888'
},
series: [
{ dataField: 'S&P 500', displayText: 'S&P 500' },
{ dataField: 'NASDAQ', displayText: 'NASDAQ' }
]
}
]
};
// setup the chart
$('#jqxChart').jqxChart(settings);
}
// init widgets.
var initWidgets = function (tab) {
switch (tab) {
case 0:
initGrid();
break;
case 1:
initChart();
break;
}
}
$('#jqxTabs').jqxTabs({ width: 600, height: 560, initTabContent: initWidgets });
});
</script>
</head>
<body class='default'>
<div id='jqxWidget'>
<div id='jqxTabs'>
<ul>
<li style="margin-left: 30px;">
<div style="height: 20px; margin-top: 5px;">
<div style="float: left;">
<img width="16" height="16" src="../../images/catalogicon.png" />
</div>
<div style="margin-left: 4px; vertical-align: middle; text-align: center; float: left;">
US Indexes</div>
</div>
</li>
<li>
<div style="height: 20px; margin-top: 5px;">
<div style="float: left;">
<img width="16" height="16" src="../../images/pieicon.png" />
</div>
<div style="margin-left: 4px; vertical-align: middle; text-align: center; float: left;">
NASDAQ compared to S&P 500</div>
</div>
</li>
</ul>
<div style="overflow: hidden;">
<div id="jqxGrid">
</div>
<div style="margin-top: 10px; height: 15%;">
The S&P 500 index finished 2011 less than a point away from where it ended 2010
-- 0.04 points down to be exact. That's the smallest annual change in history. At
its peak in April, the S&P had climbed more than 8%. But by October, at the lowest
levels of the year, it was down more than 12%. The Nasdaq, meanwhile, lost 1.8%
for the year.</div>
</div>
<div style="overflow: hidden;">
<div id='jqxChart' style="width: 100%; height: 100%">
</div>
</div>
</div>
</div>
</body>
</html>

Categories