jHeatmap Javascript library tab behaves strangely - javascript

I have been struggling with this problem for days and it really baffled me. Hopefully someone skillful in JQuery could help out.
This is related to a very powerful and nice javascript library for creating interactive heatmaps. http://jheatmap.github.io/jheatmap/. I am modifying one of the examples -- Quickstart -- in order to display more than one heatmap on a page. The idea is to put heatmap on separate tabs and activate a heatmap by clicking on a particular tab. The tool couldn't do this naturally, instead it only displays one heatmap on each html page. The developer suggested a solution but here is the problem.
In this sample code, I intend to display three heatmaps (call them heatmap1, heatmap2 and heatmap3) on three tabs. The current situation is that I must click on heatmap1's tab first before clicking on tabs for heatmap2 or heatmap3. Since heatmap1 is displayed by default, so when the page is initially up, I can just go ahead to click on tab's for heatmap2 and that is fine. But now if I want to display heatmap3, I must go back to click on heatmap1's tab, then click on heatmap3's tab. After I manage to see heatmap3 using this trick, I will need to click on heatmap1's tab again in order to display heatmap2. It seems heatmap1 must be displayed before any other heatmaps to be shown.
Since my account won't allow me to attach a file, I put the code below. This is a direct modification of the Jheatmap's QuickStart step4 code. You will not be able to run it because the script loads/reads in text files. But I would greatly appreciate if you can take a look at the javascript around the three heatmaps and the html codes rendering the objects. I think someone skillful in JQuery could give me some advice on how to fix the bug.
Thanks much for your help.
<!DOCTYPE html>
<html>
<head>
<title>jHeatmap</title>
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">
<link href="prettify.css" rel="stylesheet" type="text/css">
<link href="../../styles/jheatmap-1.0.0.css" rel="stylesheet" type="text/css"/>
<style>
/* To center the heatmap */
table.heatmap {
margin: 0px auto;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.js"></script>
<script src="../../scripts/jheatmap-1.0.0.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
/* heatmap1 */
$('#heatmap1').heatmap(
{
data: {
rows: new jheatmap.readers.AnnotationReader({ url: "quickstart-rows.tsv" }),
cols: new jheatmap.readers.AnnotationReader({ url: "quickstart-cols.tsv" }),
values: new jheatmap.readers.TableHeatmapReader({ url: "quickstart-data.tsv" })
},
init: function (heatmap) {
// Column annotations
heatmap.cols.decorators["subtype2"] = new jheatmap.decorators.CategoricalRandom();
heatmap.cols.annotations = ["subtype"];
// Rows annotations
heatmap.rows.decorators["fm-bias"] = new jheatmap.decorators.PValue({ cutoff: 0.05 });
heatmap.rows.annotations = ["fm-bias"];
// Aggregators
heatmap.cells.aggregators["Mutation"] = new jheatmap.aggregators.AbsoluteAddition();
heatmap.cells.aggregators["CNA Status"] = new jheatmap.aggregators.AbsoluteAddition();
heatmap.cells.aggregators["Expression"] = new jheatmap.aggregators.Median();
// Decorators
heatmap.cells.decorators["Mutation"] = new jheatmap.decorators.Categorical({
values: ["0","1"],
colors : ["white","green"]
});
heatmap.cells.decorators["CNA Status"] = new jheatmap.decorators.Categorical({
values: ["-2","2"],
colors : ["blue","red"]
});
heatmap.cells.decorators["Expression"] = new jheatmap.decorators.Heat({
minValue: -2,
midValue: 0,
maxValue: 2,
minColor: [85, 0, 136],
nullColor: [255,255,255],
maxColor: [255, 204, 0],
midColor: [240,240,240]
});
}
});
/* heatmap2 */
$('#myTab a').click(function (e) {
e.preventDefault();
$(this).tab('show');
// Load Heatmap2
if ($(this).tab()[0].hash == '#heatmap2Tab') {
$('#heatmap-loader').show();
$('#heatmap2').width($('#heatmap').width());
$('#heatmap2').heatmap(
{
data: {
rows: new jheatmap.readers.AnnotationReader({ url: "quickstart-rows.tsv" }),
cols: new jheatmap.readers.AnnotationReader({ url: "quickstart-cols.tsv" }),
values: new jheatmap.readers.TableHeatmapReader({ url: "quickstart-data.tsv" })
},
init: function (heatmap) {
// Column annotations
heatmap.cols.decorators["subtype"] = new jheatmap.decorators.CategoricalRandom();
heatmap.cols.annotations = ["subtype"];
// Rows annotations
heatmap.rows.decorators["fm-bias"] = new jheatmap.decorators.PValue({ cutoff: 0.05 });
heatmap.rows.annotations = ["fm-bias"];
// Aggregators
heatmap.cells.aggregators["Mutation"] = new jheatmap.aggregators.AbsoluteAddition();
heatmap.cells.aggregators["CNA Status"] = new jheatmap.aggregators.AbsoluteAddition();
heatmap.cells.aggregators["Expression"] = new jheatmap.aggregators.Median();
// Decorators
heatmap.cells.decorators["Mutation"] = new jheatmap.decorators.Categorical({
values: ["0","1"],
colors : ["white","green"]
});
heatmap.cells.decorators["CNA Status"] = new jheatmap.decorators.Categorical({
values: ["-2","2"],
colors : ["blue","red"]
});
heatmap.cells.decorators["Expression"] = new jheatmap.decorators.Heat({
minValue: -2,
midValue: 0,
maxValue: 2,
minColor: [85, 0, 136],
nullColor: [255,255,255],
maxColor: [255, 204, 0],
midColor: [240,240,240]
});
}
});
}
})
/* heatmap3 */
$('#myTab a').click(function (e) {
e.preventDefault();
$(this).tab('show');
// Load Heatmap2
if ($(this).tab()[0].hash == '#heatmap3Tab') {
$('#heatmap-loader').show();
$('#heatmap3').width($('#heatmap').width());
$('#heatmap3').heatmap(
{
data: {
rows: new jheatmap.readers.AnnotationReader({ url: "quickstart-rows.tsv" }),
cols: new jheatmap.readers.AnnotationReader({ url: "quickstart-cols.tsv" }),
values: new jheatmap.readers.TableHeatmapReader({ url: "quickstart-data.tsv" })
},
init: function (heatmap) {
// Column annotations
heatmap.cols.decorators["subtype"] = new jheatmap.decorators.CategoricalRandom();
heatmap.cols.annotations = ["subtype"];
// Rows annotations
heatmap.rows.decorators["fm-bias"] = new jheatmap.decorators.PValue({ cutoff: 0.05 });
heatmap.rows.annotations = ["fm-bias"];
// Aggregators
heatmap.cells.aggregators["Mutation"] = new jheatmap.aggregators.AbsoluteAddition();
heatmap.cells.aggregators["CNA Status"] = new jheatmap.aggregators.AbsoluteAddition();
heatmap.cells.aggregators["Expression"] = new jheatmap.aggregators.Median();
// Decorators
heatmap.cells.decorators["Mutation"] = new jheatmap.decorators.Categorical({
values: ["0", "1"],
colors: ["white", "green"]
});
heatmap.cells.decorators["CNA Status"] = new jheatmap.decorators.Categorical({
values: ["-2", "2"],
colors: ["blue", "red"]
});
heatmap.cells.decorators["Expression"] = new jheatmap.decorators.Heat({
minValue: -2,
midValue: 0,
maxValue: 2,
minColor: [85, 0, 136],
nullColor: [255, 255, 255],
maxColor: [255, 204, 0],
midColor: [240, 240, 240]
});
}
});
}
})
});</script>
</head>
<body>
<div class="container">
<div class="row">
<ul class="nav nav-pills">
<li>Step 0</li>
<li>Step 1</li>
<li>Step 2</li>
<li>Step 3</li>
<li class="active">Step 4</li>
<li>Step 5</li>
</ul>
<p>
Add column and row annotation headers.
</p>
</div>
<div class="row">
<div id="heatmap-loader">
<div class="background"></div>
<div class="loader">
<img src="../../images/loading.gif">
</div>
</div>
<ul id="myTab" class="nav nav-tabs">
<li class="active">Heatmap1</li>
<li>Heatmap2</li>
<li>Heatmap3</li>
<li>Javascript</li>
<li>quickstart-data.tsv</li>
<li>quickstart-cols.tsv</li>
<li>quickstart-rows.tsv</li>
</ul>
<div id="myTabContent" class="tab-content">
<div class="tab-pane fade in active" id="heatmap1Tab" style="">
<div id="heatmap1"></div>
</div>
<div class="tab-pane fade" id="heatmap2Tab" style="">
<div id="heatmap2" style="width:100%;"></div>
</div>
<div class="tab-pane fade" id="heatmap3Tab" style="">
<div id="heatmap3" style="width:100%;"></div>
</div>
<div class="tab-pane fade" id="javascriptTab">
<pre id="source" class="prettyprint linenums"></pre>
</div>
<div class="tab-pane fade" id="dataTab">
<pre id="data" class="prettyprint"></pre>
</div>
<div class="tab-pane fade" id="cdataTab">
<pre id="cdata" class="prettyprint"></pre>
</div>
<div class="tab-pane fade" id="rdataTab">
<pre id="rdata" class="prettyprint"></pre>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="prettify.js"></script>
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script>
var source = document.getElementsByTagName('script')[2].innerHTML;
source = source.replace(/</g, "<").replace(/>/g, ">");
$('#source').html(source);
window.prettyPrint && prettyPrint();
$('#source ol.linenums li').each(function(idx, li) {
if ((idx > 3 && idx < 6) || (idx > 10 && idx < 18)) {
$(li).css("background-color", "#FFFFB3");
}
});
jQuery.ajax({
url: "quickstart-data.tsv",
dataType: "text",
success: function (file) {
$('#data').html(file);
}
});
jQuery.ajax({
url: "quickstart-cols.tsv",
dataType: "text",
success: function (file) {
$('#cdata').html(file);
}
});
jQuery.ajax({
url: "quickstart-rows.tsv",
dataType: "text",
success: function (file) {
$('#rdata').html(file);
}
});
</script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-7336589-2', 'jheatmap.github.io');
ga('send', 'pageview');
</script>
</body>
</html>

I think that the main problem in your code is that you are binding two functions to all the click tab events. You only need to bind one function and this function will draw only one heatmap depending on the link that was clicked.
Here you have a simplified version that draws three heatmaps on different tabs:
<html>
<head>
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">
<link href="http://jheatmap.github.io/jheatmap/css/jheatmap-1.0.0-min.css" rel="stylesheet" type="text/css"/>
<script src="http://code.jquery.com/jquery-1.10.1.js"></script>
<script src="http://jheatmap.github.io/jheatmap/js/jheatmap-1.0.0-min.js"></script>
<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script>
var draw_heatmap = function (tag_id) {
$('#'+tag_id).heatmap({
data: {
values: new jheatmap.readers.TableHeatmapReader({ url: "http://jheatmap.github.io/jheatmap/examples/quickstart/quickstart-data.tsv" })
}});
};
$(document).ready(function () {
/* Draw the default visible heatmap */
draw_heatmap('heatmap1');
/* Calculate the visible heatmap width */
var heatmap_width = $('#heatmap1').width();
/* Fix the width to all the heatmaps */
$('#heatmap1').width(heatmap_width);
$('#heatmap2').width(heatmap_width);
$('#heatmap3').width(heatmap_width);
/* Attach draw heatmap to tab click event */
$('#myTab a').click(function (e) {
e.preventDefault();
/* Show the clicked tab */
$(this).tab('show');
/* Show the loader indicator */
$('#heatmap-loader').show();
/* Draw the correct heatmap */
if ($(this).tab()[0].hash == '#heatmap1Tab') {
draw_heatmap('heatmap1');
}
if ($(this).tab()[0].hash == '#heatmap2Tab') {
draw_heatmap('heatmap2');
}
if ($(this).tab()[0].hash == '#heatmap3Tab') {
draw_heatmap('heatmap3');
}
});
});
</script>
</head>
<body>
<div class="container">
<div class="row">
<div id="heatmap-loader">
<div class="background"></div>
<div class="loader">
<img src="http://jheatmap.github.io/jheatmap/images/loading.gif">
</div>
</div>
<ul id="myTab" class="nav nav-tabs">
<li class="active">Heatmap1</li>
<li>Heatmap2</li>
<li>Heatmap3</li>
</ul>
<div id="myTabContent" class="tab-content">
<div class="tab-pane fade in active" id="heatmap1Tab">
<div id="heatmap1"></div>
</div>
<div class="tab-pane fade" id="heatmap2Tab">
<div id="heatmap2"></div>
</div>
<div class="tab-pane fade" id="heatmap3Tab">
<div id="heatmap3"></div>
</div>
</div>
</div>
</div>
</body>
</html>

Related

How to make one datefilter for multiple charts on one webpage?

can someone help me with the code? I am a newbie programmer. I make a web to monitor something. Right now the data monitoring is still a dummy data. The data is on API http://66.42.52.94:8000/api/data/ . So there are so many sensors data (which are: accelero_x, accelero_y, accelero_z, vibration, moisture, gyro_x, gyro_y, gyro_z, displacement) that I have to display on the chart. And this one is the code for displaying the chart of accelerometer sensor x-axes.
code for js file :
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$("#firstdatepicker").datepicker();
$("#lastdatepicker").datepicker();
$("#filter").click(function() {
var from_date = $("#firstdatepicker").val();
var to_date = $("#lastdatepicker").val();
if (from_date != '' && to_date != '') {
console.log(from_date, to_date);
var endpoint = '/api/data';
$.ajax({
method: "GET",
url: endpoint,
data: {
from_date: from_date,
to_date: to_date
},
success: function(data){
console.log(data); //get all data
//get data by fields
var accelero_x = [], time = [];
for (var i=0; i<data.length; i++){
accelero_x.push(data[i].accelero_x);
time.push(data[i].timestamp);
}
console.log(accelero_x);
console.log(time);
//plot the chart
var ctx = document.getElementById("acceleroxChart").getContext('2d');
var acceleroxChart = new Chart(ctx, {
type: 'line',
data: {
labels: time,
datasets: [{
label: 'Accelero-x (mV/g)',
data: accelero_x,
fill: false,
borderColor: "#80b6f4",
pointBorderColor: "#80b6f4",
pointBackgroundColor: "#80b6f4",
pointHoverBackgroundColor: "#80b6f4",
pointHoverBorderColor: "#80b6f4",
pointBorderWidth: 10,
pointHoverRadius: 10,
pointHoverBorderWidth: 1,
pointRadius: 1,
borderWidth: 4,
}]
},
options: {
reponsive: true,
scales: {
yAxes: [{
ticks: {
beginAtZero:false,
stepSize:0.5
},
scaleLabel: {
display: true,
labelString: 'Accelero sb.x (mV/g)'
}
}],
xAxes: [{
display: true,
type: "time",
time: {
minUnit: "hour",
unit: "hour",
unitStepSize: 6,
min: moment(from_date).toDate(),//Date object type
max: moment(to_date).toDate()//Date object type
},
scaleLabel: {
display: true,
labelString: 'Time'
}
}]
}
}
});
},
error: function(error_data){
console.log(error_data)
}
});
} else {
alert("Please Select Date");
}
});
});
code for html:
{% extends 'base.html' %}
{% load static %}
{% block content %}
<!-- Begin Page Content -->
<div class="container-fluid">
<!--card header-->
<div class="card-header">
<h6 class="m-0 font-weight-bold text-primary">Accelero X-axes</h6>
<!--Breadcrumbs-->
<ol class="breadcrumb">
<li style="margin-left: 10px">
data from <input type="text" id="firstdatepicker" name="firstdatepicker" value="2020-03-15">
to <input type="text" id="lastdatepicker" name="lastdatepicker" value="2020-03-16">
<input type="button" name="filter" id="filter" value="Filter" class="btn btn-info">
</li>
</ol>
<!--End of breadcrumbs date picker-->
<!--Kelembaban tanah Area Chart-->
<div class="card-body">
<div class="chart-area">
<canvas id="acceleroxChart"></canvas>
</div>
</div> <!--end of area chart-->
</div> <!--end of card header-->
</div>
<!--end of page content (container-fluid) -->
</div>
<!-- End of Main Content -->
</div>
<!-- End of Content Wrapper -->
</div>
<!-- End of Page Wrapper -->
<!-- Scroll to Top Button-->
<a class="scroll-to-top rounded" href="#page-top">
<i class="fas fa-angle-up"></i>
</a>
<!-- Page level chart.js yang digunakan halaman ini-->
<script src="{% static 'js/demo/accelero-x.js' %}"></script>
<!-- <script src="{% static 'js/demo/chart-pie-demo.js' %}"></script> -->
<!-- date picker js-->
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3/dist/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/jquery.ui.datepicker.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<!--buat kalender-->
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/themes/sunny/jquery-ui.min.css"></link>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css"></link>
{% endblock content %}
So x-axes of the chart for time and y-axes of the chart for sensors data. And the data can be filtered by the datefilter that I picked like this :
These codes only display a chart for accelerometer sensors x-axes on one webpage. The problem is I want to display all of the charts of each sensor (so by the end there will be 9 charts) on one single page with just one datefilter for all the charts. Can someone help me with the code? Thank you before.
I solved it! It doesn't need any special code.
Just call the other charts to the html part. No need to iterate the breadcrumbs part on html.
<div class="card-body">
<div class="chart-area">
<canvas id="acceleroxChart"></canvas>
</div>
</div> <!--end of area chart-->
<br>
<h2>Chart2</h2>
<br>
<div class="card-body">
<div class="chart-area">
<canvas id="theotherchartname"></canvas>
</div>
</div>
.........and so on....
You can still use the the same structure code as the js file above for the other charts sensor, just change the data you need.

Creating HTML objects from javascript object then move them on click

I am working on a homework problem where 4 characters appear in a row, one is clicked and stays, the others move to a new row. Once in that row another is clicked again to be the opponent and that one moves to a new row for the fight.
I was going to build the character cards using jquery and move them with that as well. I tried using a for loop but it iterates each character in the object in each character column instead of doing one each. The end result is all 4 of the character names appear in the first column, then just the last 3, then just the last 2, and then the last one. I am trying to iterate through so the first column contains the name, picture, and hitpoints of the first character and repeat for each character.
As far as moving the character cards around, I was going to try to detach and prepend to the target row but my click function is returning an undefined instead of the name of the character selected.
I tried an alternate method but that is not working either. Both are included in the code
Main JS File
$(document).ready(function(){
/*
- make object for each playable character
- for each character make a variable for their hitpoints
*/
var characters = [
{
name: "Rey",
hitPoints: 150,
counterattack: 20,
picture: "../images/rey-red-saber.jpg"
},
{
name: "Boba Fett",
hitPoints: 100,
counterattack: 50,
picture: "../images/Boba2.jpeg"
},
{
name: "Grievous",
hitPoints: 200,
counterattack: 10,
picture: "../images/Grievous.jpg"
},
{
name: "Phasma",
hitPoints: 180,
counterattack: 15,
picture: "../images/Phasma.jpg"
}
]
for(var i = 0; i< characters.length; i++){
$(".charRow").append("<div class='col-md-2 charCol'></div>");
$(".charCol").append("<div class='card text-center charCard'></div>");
$(".charCard").append("<div class='card-header'>" + characters[i].name + "</div>");
// $(".card-header").html("<img class='card-img-top charImg' src=" + characters)
}
});
Alternate JS file
///var chosen;
var myChar = "";
var characters = {
rey: {
name: "Rey",
hitPoints: 150,
counterattack: 20
},
boba: {
name: "Boba Fett",
hitPoints: 100,
counterattack: 50
},
grievous: {
name: "Grievous",
hitPoints: 200,
counterattack: 10
},
phasma: {
name: "Phasma",
hitPoints: 180,
counterattack: 15
}
};
$(document).ready(function(){
/*
- make object for each playable character
- for each character make a variable for their hitpoints
*/
$(".charCol").click(function(){
if(myChar == "") {
myChar = $(this);
console.log(myChar);
chosen = $(myChar).attr("value");
console.log(chosen)
};
// console.log(chosen)
if(chosen == "rey"){
}
});
});
HTML PAGE
<!DOCTYPE html>
<head>
<title>The Force Is Strong Here</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="assets/javascript/game.js"></script>
<link href="https://fonts.googleapis.com/css?family=Faster+One|Geostar+Fill&display=swap" rel="stylesheet">
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body class="background">
<div class="container">
<div class="row">
<div class="col-md-12 titleContainer">
<div id="title">Star Wars RPG</div>
</div>
</div>
<div class="row charRow">
</div>
<div class="row titleRow">
<div class="col-md-12">
<h2 class="charTitle">Your Character</h2>
</div>
</div>
<div class="row enemyRow">
</div>
<div class="row titleRow">
<div class="col-md-12">
<h2 class="charTitle">Enemies Available To Attack</h2>
</div>
</div>
<div class="row titleRow">
<div class="col-md-12">
<h2 class="charTitle">Fight Section</h2>
</div>
</div>
<div class="row titleRow">
<div class="col-md-12">
<h2 class="charTitle">Defender</h2>
</div>
</div>
<div class="row">
<div class="col-md-2 charCol">
<button type="button" class="btn btn-dark">Attack</button>
</div>
</div>
</div>
<script src="" async defer></script>
</body>
</html>

Trying to load a google chart through a click event - get the error: Uncaught Error: Map container not found

I am trying to load a google chart through a jquery ajax call by clicking on a geojson layer, which is loaded over a map. I'm using the leaflet API for the map creation and for its layers and the google charts API for creating the chart. When I'm trying to load the page, it won't finish loading and it gives me the following error: Uncaught Error: Map container not found.
When I click on the error in the console, it takes me to the leaflet library where this part is marked as an error: ".get(t);if(!e)throw new Error("Map container not found.");if(e._leaflet)throw new Error("Map container is already initialized.");e._leaflet=!0},_initLayout:function(){var t=this._container;o.DomUtil.addClass(t,"leaflet-container"+(o.Browser.touch?" leaflet-t..."
When I'm commenting out the code for the chart, the page loads with the map without a problem.
I'm using these js libraries for the chart and the map:
<script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
My code for the chart, the geojson and the map is as follows:
function drawChart() {
var jsonData = $.ajax({
url: "http://climatedataapi.worldbank.org/climateweb/rest/v1/country/cru/tas/year/" + feature.properties.ISO3.jsonp,
data: {page: 1, format: "jsonp", prefix: "getdata"},
crossDomain: true,
jsonpCallback: "getdata",
}).done(function (results) {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Year');
data.addColumn('number', 'Temp');
$.each(results, function (i, row) {
data.addRow([
(new Date(row.year)),
parseFloat(row.data),
]);
});
var chart = new google.visualization.LineChart(document.getElementById("container"));
chart.draw(data, {
title: 'Annual Average Temperature'
});
})//end function
}//end drawChart
google.load('visualization', '1', {
packages: ['corechart']
});
var aLayerThree = L.geoJson(aGeoJson, {
style: function (feature) {
return {stroke: true, color: "#3333ff", weight: 2, fillOpacity: 0};
},
onEachFeature: function (feature, layer) {
layer.on('mouseover', function() {
layer.setStyle({fillColor: "#4da6ff", fillOpacity: 0.4});
aDiv.innerHTML = feature.properties.NAME;
layer.on('mouseout', function() {
layer.setStyle({ fillOpacity: 0});
aDiv.innerHTML = "Web-Mapping Techniques";
$('layer').on('click', function() {
drawChart();
})// end click
})// end mouseout
})//end mousover
} // end onEachFeature
});// end GeoJson
//Create our Map Object
map = L.map('myMap', {
fullscreenControl: true,
center: centerlatlng,
minZoom: 2,
zoom: 4,
layers: [aLayerOne, aLayerThree]
});
My html looks like that:
<body>
<div class="container-fluid">
<div class="row">
<!--<br />-->
</div><!-- Row 1 -->
<div class="row">
<nav class="col-lg-10 col-lg-offset-1 navbar navbar-default" role="navigation">
<a class="navbar-brand" href="#">Annual Temperature and Precipitation by Country</a>
<ul class="nav navbar-nav pull-right">
<li class="active">Info</li>
<li>About</li>
</ul>
</nav>
</div><!-- Row 2 -->
<div class="row">
<div id="myMap" class="col-lg-10 col-lg-offset-1"></div>
</div><!-- Row 3 -->
<div class="row">
<br/>
</div><!-- Row 4 -->
<div class="row">
<div id="container" style="width:100%; height:400px;"></div>
</div><!-- Row 5 -->
</div>
I am a newbie in creating charts. What am I doing wrong?
Thanks in advance!

Photoswipe and Infinite AJAX Scroll

First up, apologies for lots of code. Just don't want to miss anything.
I am generating images on a page in this format:
<!DOCTYPE html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js" type="text/javascript"></script>
<!-- photoswipe Core CSS file -->
<link rel="stylesheet" href="assets/photoswipe/dist/photoswipe.css">
<link rel="stylesheet" href="assets/photoswipe/dist/default-skin/default-skin.css">
</head>
<body>
<div id="page">
<div id="thumbs" itemscope itemtype="http://schema.org/ImageGallery">
<ul class="responsive-thumbnails" data-max-width="202px" data-padding="4px">
<li class="thumb">
<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
<img src="img/th_31.jpg" itemprop="thumbnail" alt="" />
</figure>
</li>
<!-- multiple of <li> as above here for each thumbnail image -->
</ul>
</div>
<div id="pagination"><!-- my codeigniter paginiation output (gets hidden by infintie scroll</div>
</div>
<!-- Infinite AJAX Scroll stuff -->
<script type="text/javascript" src="assets/jquery-ias.min.js"></script>
<script type="text/javascript">
var ias = $.ias({
container: "#thumbs",
item: ".thumb",
pagination: "#pagination",
next: ".next a"
});
ias.extension(new IASSpinnerExtension());
ias.extension(new IASTriggerExtension({offset: 5}));
ias.extension(new IASNoneLeftExtension({text: 'There are no more pages left to load.'}));
/* //I think somehow here, I need to trigger photoswipe to add new items after IAS has added more.
ias.on('rendered', function(items) {
lightBox.init();
);
});
*/
</script>
<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
<!-- this is where the standard photoswipe html elements are stored. Copied from their docs. Omitted here -->
</div>
<!-- photoswipe Core JS file -->
<script src="assets/photoswipe/dist/photoswipe.min.js"></script>
<script src="assets/photoswipe/dist/photoswipe-ui-default.min.js"></script>
<!-- my script to initiate Photoswipe instance (see below) -->
<script type="text/javascript" src="assets/photoswipe.js"></script>
</body>
</html>
Contents of photoswipe.js:
(function($) {
var $pswp = $('.pswp')[0];
var image = [];
$('#thumbs').each( function() {
var $pic = $(this),
getItems = function() {
var items = [];
$pic.find('a').each(function() {
var $href = $(this).attr('href'),
$size = $(this).data('size').split('x'),
$width = $size[0],
$height = $size[1];
var item = {
src : $href,
w : $width,
h : $height
}
items.push(item);
});
return items;
}
var items = getItems();
console.log(items);
$.each(items, function(index, value) {
image[index] = new Image();
image[index].src = value['src'];
});
$pic.on('click', 'li', function(event) {
event.preventDefault();
var $index = $(this).index();
var options = {
index: $index,
bgOpacity: 0.7,
showHideOpacity: true,
showAnimationDuration: 500,
hideAnimationDuration: 500
}
var lightBox = new PhotoSwipe($pswp, PhotoSwipeUI_Default, items, options);
lightBox.init();
});
});
})(jQuery);
Photoswipe is working, but it only works with the first batch of photo initially loaded on the page. In this case I load 20. Any more images that get appended by IAS can be clicked on and do bring up the photoswipe lightbox, but their preview sized images are not showing in the lightbox. I just get the first 20 to scroll through.
So the question is, how do I get photoswipe and Infinite AJAX Scroll to work together?

Sly Scroller Jquery

i would like to use following plugin http://darsa.in/sly/ but i cant get it to work, here are some details to my code.
i have following HTML:
<div class="scroller">
<div class="scrollbar">
<div class="handle" style="-webkit-transform: translateZ(0px) translateX(0px);"></div>
</div>
<div class="sly" style="overflow: hidden;">
<ul class="slidee" style="-webkit-transform: translateZ(0);">
<li><div style="width:50px;height:50px;overflow:hidden"><img src="/images/users/7.jpg"></div></li>
<li><div style="width:50px;height:50px;overflow:hidden"><img src="/images/users/7.jpg"></div></li></ul>
</div>
</div>
and following JS:
$(document).find(".scroller").each(function (i, element) {
var $cont = $(element),
$frame = $cont.find(".sly"),
$scrollbar = $cont.find(".scrollbar");
$frame.sly({
// Sly type
horizontal: 1, // Change to horizontal direction.
itemNav: null, // Item navigation type. Can be: basic, smart, centered, forceCentered.
// Scrollbar
scrollBar: $scrollbar, // Selector or DOM element for scrollbar container.
dragHandle: 0, // Whether the scrollbar handle should be dragable.
dynamicHandle: 0, // Scrollbar handle represents the relation between hidden and visible content.
minHandleSize: 50, // Minimal height or width (depends on sly direction) of a handle in pixels.
clickBar: 0, // Enable navigation by clicking on scrollbar.
syncFactor: 0.50, // Handle => SLIDEE sync factor. 0-1 floating point, where 1 = immediate, 0 = infinity.
});
$frame.sly('reload');
});
But somehow Sly-Scroller doesn't work? Thanks for help!
First of all Load all the Scripts for SLY in the end of your body :
<script src="js/jquery.easing.js"></script>
<script src="sly/horizontal.js"></script>
<script src="http://darsa.in/sly/js/vendor/modernizr.js"></script>
<script src="http://darsa.in/sly/js/sly.min.js" ></script>
Then Call the HTML like this :
<div id="navigation">
<div class="wrap">
<h2>Video Playlist</h2>
<div class="scrollbar" style = "width:100%">
<div class="handle">
<div class="mousearea"></div>
</div>
</div>
<div class="frame " id="basic">
<ul class="clearfix">
<li> </li>
</ul>
</div>
<ul class="pages"></ul>
</div>
</div>
here you go! Credit goes to this blog writer...
don't forget to click on "download", see more details there!
http://www.okilla.com/614/plugin-sly-scrolling-with-item-based-navigation-support/
try this, its work for me
$(document).find('.row').each(function () {
var $slider = $(this).find('#contentSlider');
var $wrap = $slider.parent();
$slider.sly({
horizontal: 1,
itemNav: 'basic',
smart: 1,
activateOn: 'click',
mouseDragging: 1,
touchDragging: 1,
releaseSwing: 1,
startAt: 1,
scrollBar: $wrap.find('.scrollbar'),
scrollBy: 1,
pagesBar: $wrap.find('.pages'),
activatePageOn: 'click',
speed: 300,
elasticBounds: 1,
easing: 'easeOutExpo',
dragHandle: 1,
dynamicHandle: 1,
clickBar: 1
});
});

Categories