html div table to export excel - html

On my UI where I have open source project,
https://github.com/townsean/canvas-pixel-color-counter
so what I am trying to do is :-
I want to export HTML data into excel,all input div count data, earlier I was using exporting to excel plugin but it is only exporting the HTML table data not input fields data
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="author" content="Ashley G">
<meta name="description" content="A web app that counts the number of pixels in an image per a unique color.">
<title>Pixel Color Counter</title>
<link rel="shortcut icon" href="./assets/favicon.ico" type="image/x-icon">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link href="https://fonts.googleapis.com/css?family=Press+Start+2P&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Open+Sans&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<button onclick="exportTableToExcel('tblData')">Export Table Data To Excel File</button>
</head>
<body>
<header>
<h1>Pixel Color Counter</h1>
</header>
<main>
<!-- About Section -->
<section id="about">
<h2>Count Pixels by Color</h2>
<p>Pixel Color Counter is vanilla JS web application that accepts an image file (selected by the user) and displays the total number of pixels per a unique color. </p>
</section>
<!-- Upload Image Section -->
<section id="upload-container">
<h2>Upload an Image</h2>
<div>
<label for="image">Choose an image:</label>
<input type="file" id="image" name="image" accept="image/png, image/jpeg">
</div>
<canvas id="canvas"></canvas>
</section>
<!-- Pixel Color Swatches and Count -->
<section id="pixel-count-container" class="pixel-count-container invisible">
<h2>Pixel Counts by Color</h2>
<p><span id="color-count"></span> unique colors</p>
<div id="color-swatches" class="color-swatches">
</div>
</section>
</main>
<div id="wait-indicator" class="invisible">
<img src="assets/ashley_sprite.gif">
<p>Please Wait</p>
</div>
<footer>
Copyright © 2019 Ashley Grenon
</footer>
<script src="counter.js"></script>
<script src="main.js"></script>
</body>
</html>
and jquery
and counter js this project
// https://developer.mozilla.org/en-US/docs/Tools/Performance/Scenarios/Intensive_JavaScript
self.addEventListener("message", go);
/**
*
*/
function go(message) {
const imageData = message.data.imageData;
const colorCounts = countPixels(imageData);
self.postMessage({
"command": "done",
colorCounts
});
}
/**
* Counts the number of pixels per a unique color
* https://stackoverflow.com/questions/19499500/canvas-getimagedata-for-optimal-performance-to-pull-out-all-data-or-one-at-a
*/
function countPixels(data) {
const colorCounts = {};
for(let index = 0; index < data.length; index += 4) {
const rgba = `rgba(${data[index]}, ${data[index + 1]}, ${data[index + 2]}, ${(data[index + 3] / 255)})`;
if (rgba in colorCounts) {
colorCounts[rgba] += 1;
} else {
colorCounts[rgba] = 1;
}
}
return colorCounts;
}
and main.js
// To avoid Uncaught DOMException while using Web Workers
// Run python -m http.server 8000
// https://stackoverflow.com/questions/8170431/using-web-workers-for-drawing-using-native-canvas-functions
const worker = new Worker('./counter.js');
handleWorkerCompletion = (message) => {
if(message.data.command == "done") {
// draw color swatches
this.drawColorSwatch(message.data.colorCounts);
worker.removeEventListener("message", handleWorkerCompletion);
// hide wait indicator
const waitIndicator = document.getElementById("wait-indicator");
waitIndicator.classList.add("invisible");
waitIndicator.classList.remove("fadein");
// scroll to color swatch section
const pixelCountContainer = document.getElementById('pixel-count-container');
pixelCountContainer.scrollIntoView({ behavior: 'smooth'});
const colorCountLabel = document.getElementById('color-count');
colorCountLabel.innerText = Object.keys(message.data.colorCounts).length;
}
};
/**
* Event listener for when the file upload has been updated
*/
document.getElementById("image").addEventListener('change', (e) => {
this.loadImage(e.target.files[0]);
}, false);
/**
* Given a valid image file, load the image into the canvas
* Good explantation the the image data: https://css-tricks.com/manipulating-pixels-using-canvas/#article-header-id-1
*/
loadImage = (file) => {
const url = window.URL.createObjectURL(file);
const img = new Image();
img.src = url;
img.onload = () => {
this.reset();
const canvas = document.getElementById('canvas');
canvas.width = img.width;
canvas.height = img.height;
const context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
const uploadContainer = document.getElementById('upload-container');
uploadContainer.appendChild(img);
const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
window.URL.revokeObjectURL(this.src);
worker.addEventListener("message", handleWorkerCompletion, false);
worker.postMessage({
"imageData": imageData.data
});
const waitIndicator = document.getElementById("wait-indicator");
waitIndicator.classList.remove("invisible");
waitIndicator.classList.add("fadein");
}
};
/**
*
*/
drawColorSwatch = (colorCount) => {
let colorSwatches = document.getElementById('color-swatches');
for(const color in colorCount) {
const container = document.createElement("section");
const swatch = document.createElement("div");
const colorCountLabel = document.createElement("span");
container.classList.add("color-swatch-container");
swatch.classList.add("color-swatch");
swatch.style.background = color;
swatch.title = color;
colorCountLabel.innerHTML = `: ${colorCount[color]}`;
container.appendChild(swatch);
container.appendChild(colorCountLabel);
colorSwatches.appendChild(container);
}
let pixelCountContainer = document.getElementById('pixel-count-container');
pixelCountContainer.classList.remove('invisible');
};
/**
* Clear DOM of past color counting
*/
reset = () => {
let pixelCountContainer = document.getElementById('pixel-count-container');
pixelCountContainer.classList.add('invisible');
let colorSwatches = document.getElementById('color-swatches');
while (colorSwatches.firstChild) {
colorSwatches.removeChild(colorSwatches.firstChild);
}
let uploadContainer = document.getElementById('upload-container');
let image = uploadContainer.getElementsByTagName('img')[0];
if (image) {
uploadContainer.removeChild(image);
}
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
}
function exportTableToExcel(color-swatches, filename = ''){
var downloadLink;
var dataType = 'application/vnd.ms-excel';
var tableSelect = document.getElementById(color-swatches);
var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
// Specify file name
filename = filename?filename+'.xls':'excel_data.xls';
// Create download link element
downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob){
var blob = new Blob(['\ufeff', tableHTML], {
type: dataType
});
navigator.msSaveOrOpenBlob( blob, filename);
}else{
// Create a link to the file
downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
}

Related

AmCharts4 - Unable to load file - external JSON file produced from SQL database

I'm struggling to open my json arranged data in AmCharts4. In my previous charts I used very simple script (chart.data = ;), which unfortunately does not work this time. So I'm using chart.dataSource.url function proposed by AmCharts documentation. When, I load example file found on web everything works fine, as soon as I switch to my file the chart is not able to load file. I'm not able to find a similar problem on web, therefore I would be very grateful for help.
Here is my example with working url and my not working file.
Thanks in advance:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://www.amcharts.com/lib/4/core.js"></script>
<script src="https://www.amcharts.com/lib/4/charts.js"></script>
<script src="https://www.amcharts.com/lib/4/themes/animated.js"></script>
<style>
</style>
</head>
<body>
<div id="chartdiv"></div>
</body>
</html>
<!-- Styles -->
<style>
#chartdiv {
width: 100%;
height: 500px;
}
</style>
<!-- Resources -->
<script src="https://cdn.amcharts.com/lib/4/core.js"></script>
<script src="https://cdn.amcharts.com/lib/4/charts.js"></script>
<script src="https://cdn.amcharts.com/lib/4/themes/animated.js"></script>
<!-- Chart code -->
<script>
am4core.ready(function() {
// Themes begin
am4core.useTheme(am4themes_animated);
// Themes end
var chart = am4core.create('chartdiv', am4charts.XYChart)
// Modify chart's colors
chart.colors.list = [
am4core.color("#264B29"),
am4core.color("#94B255"),
am4core.color("#456C39"),
am4core.color("#C4D563"),
am4core.color("#698F47"),
am4core.color("#F9F871"),
];
chart.legend = new am4charts.Legend()
chart.legend.position = 'top'
chart.legend.paddingBottom = 20
chart.legend.labels.template.maxWidth = 95
var xAxis = chart.xAxes.push(new am4charts.CategoryAxis())
xAxis.dataFields.category = 'year'
xAxis.renderer.cellStartLocation = 0.1
xAxis.renderer.cellEndLocation = 0.9
xAxis.renderer.grid.template.location = 0;
var yAxis = chart.yAxes.push(new am4charts.ValueAxis());
function createSeries(value, name) {
var series = chart.series.push(new am4charts.ColumnSeries())
series.dataFields.valueY = value
series.dataFields.categoryX = 'year'
series.name = name
series.events.on("hidden", arrangeColumns);
series.events.on("shown", arrangeColumns);
var bullet = series.bullets.push(new am4charts.LabelBullet())
bullet.interactionsEnabled = false
bullet.dy = 30;
bullet.label.text = '{valueY}'
bullet.label.fill = am4core.color('#ffffff')
return series;
}
// Add data
//Working url
//chart.dataSource.url = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-160/sample_data_serial.json";
//My SQL produced JSON file is not working
chart.dataSource.url = "data/my-file.php";
chart.dataSource.adapter.add("parsedData", function(data) {
var newData = [];
data.forEach(function(dataItem) {
var newDataItem = {};
Object.keys(dataItem).forEach(function(key) {
if (typeof dataItem[key] === "object") {
newDataItem["_id"] = dataItem[key]["#id"];
dataItem[key]["Column"].forEach(function(dataItem) {
newDataItem[dataItem["#name"]] = dataItem["#id"];
});
} else {
newDataItem[key] = dataItem[key];
}
});
newData.push(newDataItem);
});
data = newData;
return data;
});
createSeries('cars', 'The First');
createSeries('motorcycles', 'The Second');
createSeries('bicycles', 'The Third');
//createSeries('bilanca_lsk_lst', 'T4');
function arrangeColumns() {
var series = chart.series.getIndex(0);
var w = 1 - xAxis.renderer.cellStartLocation - (1 - xAxis.renderer.cellEndLocation);
if (series.dataItems.length > 1) {
var x0 = xAxis.getX(series.dataItems.getIndex(0), "yearX");
var x1 = xAxis.getX(series.dataItems.getIndex(1), "yearX");
var delta = ((x1 - x0) / chart.series.length) * w;
if (am4core.isNumber(delta)) {
var middle = chart.series.length / 2;
var newIndex = 0;
chart.series.each(function(series) {
if (!series.isHidden && !series.isHiding) {
series.dummyData = newIndex;
newIndex++;
}
else {
series.dummyData = chart.series.indexOf(series);
}
})
var visibleCount = newIndex;
var newMiddle = visibleCount / 2;
chart.series.each(function(series) {
var trueIndex = chart.series.indexOf(series);
var newIndex = series.dummyData;
var dx = (newIndex - trueIndex + middle - newMiddle) * delta
series.animate({ property: "dx", to: dx }, series.interpolationDuration, series.interpolationEasing);
series.bulletsContainer.animate({ property: "dx", to: dx }, series.interpolationDuration, series.interpolationEasing);
})
}
}
}
});
// end am4core.ready()
</script>
I found a typing error in my-file.php
Anyhow, after I solved typing issue the chart.dataSource.url function still did not work, but It worked using next php include script.
chart.data = <?php include './data/my-file.php'; ?>;

How do I convert this to an OOP structure?

Currently, this codepen I forked displays one tv monitor on the webpage as shown below where the channel button allows the user to toggle different gif's. This gif data is stored as an array in the js file. I want to create multiple tv sets, so I am thinking it may be better to create a TV class and instantiate the TV object n-times through a loop. I am new to OOP in a web dev context, so I haven't yet figured out how to rearchitect the code to accomplish this. Since id's only allow for one HTML element, duplicating the chunk of code below would visually create another tv but without any dynamic features. What then becomes of the tv-body display elements? Would they be enveloped with a show() fx nested with the script's TV class? Thank you so much in advance!
[Cropped Output Displayed Here][1]
HTML
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>CodePen - Vintage Analog TV</title>
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"><link rel="stylesheet" href="./style.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
<!-- partial:indexe.partial.html -->
<main>
<div class="tv-set">
<div class="tv-body">
<div class="screen-container">
<canvas class="static" width="380" height="280"></canvas>
<img class="displayed" src="" alt="Nothing" width="380" height="280">
<div class="screen">
<div class="screen-frame"></div>
<div class="screen-inset"></div>
</div>
</div>
<div class="logo-badge">
<div class="logo-text">Bush</div>
</div>
<div class="controls">
<div class="panel">
<div class="screw"></div>
<div class="dial">
<button class="channel dial-label pristine">Channel</button>
</div>
</div>
<div class="vents">
<div class="vent"></div>
<div class="vent"></div>
<div class="vent"></div>
<div class="vent"></div>
<div class="vent"></div>
<div class="vent"></div>
</div>
<div class="panel">
<div class="screw"></div>
<div class="dial">
<button class="dial-label" disabled>Volume</button>
</div>
</div>
</div>
</div>
<div class="legs">
<div class="leg"></div>
<div class="leg"></div>
</div>
</div>
</main>
<!-- partial -->
<script src="./script.js"></script>
</body>
</html>
JS
document.addEventListener("DOMContentLoaded", tv);
// Helper Functions
//returns tagname
jQuery.fn.tagName = function () {
return this.prop("tagName").toLowerCase;
};
// returns nth parent from target element
$.fn.nthParent = function (n) {
var p = this;
for (var i = 0; i < n; i++)
p = p.parent();
return p;
}
phases = [{
channels: ["red", "blue"]
},
{
channels: ["green", "yellow"]
},
{
channels: ["red", "green"]
},
{
channels: ["blue", "green"]
}
]
const container = document.getElementsByTagName("main")[0];
const template = document.getElementsByClassName("tv-set")
for (let i = 0; i < phases.length; i++) {
const clone = template[i].cloneNode(true);
clone.setAttribute("id", "tv-" + (i + 1))
console.log("clone id: ", clone.getAttribute("id"))
clone.setAttribute("data-channel", 0)
clone.setAttribute("name", "tv-" + i)
// clone.style.backgroundColor = phases[i].channels[0]
container.appendChild(clone)
}
function tv() {
let cnvs = document.querySelectorAll(".static");
//Gather all static elements
// let scrns = $(".static").getContext
// console.log("Screen 01: ", scrns)
// var cnv = document.getElementById("static"),
// var cnv = document.querySelector(".static"), //works in place of line above
// Need to establish a boolean array for the isStatic
let c = []
let isStatic_arr = []
// Need to establish a boolean array for the isStatic
cnvs.forEach((cnv) => {
isStatic_arr.push(false)
var c = cnv.getContext("2d"),
cw = cnv.offsetWidth,
ch = cnv.offsetHeight,
staticScrn = c.createImageData(cw, ch),
staticFPS = 30,
// isStatic_arr.push(false),
// isStatic = false,
staticTO,
gifData = [{
// file: "https://i.ibb.co/chSK1Zt/willie.gif",
file: "./media/back-to-school-chacha.gif",
desc: "Stephen Chow Fight Back to School"
// <video controls autoplay>
// <source src="fbts_chacha_sound.mp4" type="video/mp4">
// <source src="movie.ogg" type="video/ogg">
// Your browser does not support the video tag.
// </video>
},
{
file: "https://i.ibb.co/chSK1Zt/willie.gif",
desc: "Steamboat Willie (Mickey Mouse) steering a ship"
},
{
file: "https://i.ibb.co/0FqQVrj/skeletons.gif",
desc: "Spooky scary skeletons sending shivers down your spine"
},
{
file: "https://i.ibb.co/Hpnwgq2/kingkong.gif",
desc: "King Kong waving on Empire State Building",
},
{
file: "https://i.ibb.co/fp0PSjv/tracks.gif",
desc: "Looking at train tracks from behind a train",
},
{
file: "https://i.ibb.co/5FM7BtH/nuke.gif",
desc: "Nuclear explosion at sea",
}
],
gifs = [],
channel = 0;
for (g in gifData) {
gifs.push(new Image());
gifs[g].src = gifData[g].file;
gifs[g].alt = gifData[g].desc;
}
/* Static */
var runStatic = function () {
isStatic = true;
c.clearRect(0, 0, cw, ch);
for (var i = 0; i < staticScrn.data.length; i += 4) {
let shade = 127 + Math.round(Math.random() * 128);
staticScrn.data[0 + i] = shade;
staticScrn.data[1 + i] = shade;
staticScrn.data[2 + i] = shade;
staticScrn.data[3 + i] = 255;
}
c.putImageData(staticScrn, 0, 0);
staticTO = setTimeout(runStatic, 1e3 / staticFPS);
};
runStatic();
/* Channels */
var changeChannel = function (button, idx) {
console.log("Tv-set: ", idx)
console.log("Tv-set- " + idx + "button: " + button)
// var displayed = document.getElementById("displayed");
var displayed = document.querySelectorAll(".displayed")[idx];
var display_parent = $(".displayed")[1]
console.log("Display: ", displayed)
console.log("Display's parent: ", display_parent)
++channel;
if (channel > gifData.length)
channel = 1;
// this.classList.remove("pristine");
button.classList.remove("pristine");
// this.style.transform = `rotate(${channel * 360/(gifData.length + 1)}deg)`;
button.style.transform = `rotate(${channel * 360/(gifData.length + 1)}deg)`;
theCanvas = document.querySelectorAll(".static")[idx]
// cnv.classList.remove("hide");
theCanvas.classList.remove("hide");
displayed.classList.add("hide"); //CAUSING PROBLEMS
if (!isStatic[idx])
runStatic();
setTimeout(function () {
// cnv.classList.add("hide");
theCanvas.classList.add("hide");
displayed.classList.remove("hide");
displayed.src = gifs[channel - 1].src;
displayed.alt = gifs[channel - 1].alt;
isStatic = false;
clearTimeout(staticTO);
}, 300);
};
function iterate(item, index) {
console.log(`${item} has index ${index}`);
}
// const buttons = document.getElementsByClassName("channel dial-label pristine");
// const btns_arr = Array.from(document.querySelectorAll(".channel"))
const buttons = document.querySelectorAll(".channel")
buttons.forEach((btn, i) => {
btn.addEventListener('click', () => changeChannel(btn, i));
});
});
}
[1]: https://i.stack.imgur.com/INtzP.png
[2]: https://i.stack.imgur.com/aOxoQ.png
(11/14/20) #ggirodda, thank you so much for the example. Unfortunately, I am still a bit stuck. Why is it when I use const template = document.getElementsByClassName("tv-body").children[0], I get the error: script_001.js:154 Uncaught TypeError: Cannot read property '0' of undefined
at HTMLDocument.tv (script_001.js:154) Shouldn't the tv-body class have children based on the code snippet below?
(11/14/20) Addressed error above by removing .children[0] but unsure as to why that works and why it was undefined.
(11/19/20) Resolved! Sort of, that is. All tv clones can will run as intended, meaning the static display will remain active on all tv's whose channel button has not been pressed, and the channels can be changed independently. Here were the main changes I made on the original code:
All id's replaced with classes so that they can be accessed and wrapped the "tv-body" and "legs" in a separate div so that they can be cloned as a set.
Gathered all the "tv-set" class elements outside of the tv function() and then performed the setup functions forEach()
Converted a few of the variables e.g canvas, isStatic into arrays so that their states and displays could be toggled independently. I am sure there is more work to be done here as some of the variables may still be shared among the clones.
You can take some inspiration from the code below, the example is less complex but the idea is the same
const tvs = [
{ channels: ["red", "blue"] },
{ channels: ["green", "yellow"] }
]
function changeChannel(idx) {
const tv = tvs[idx]
const tvNode = document.getElementById("tv-" + idx)
const currentChannelIdx = parseInt(tvNode.getAttribute("data-channel"))
const nextChannelIdx = tv.channels[currentChannelIdx + 1] ? currentChannelIdx + 1 : 0;
tvNode.style.backgroundColor = tv.channels[nextChannelIdx]
tvNode.setAttribute("data-channel", nextChannelIdx)
}
const container = document.getElementById("container")
const template = document.getElementById("tv-template").children[0]
for (let i = 0; i < tvs.length; i++) {
const clone = template.cloneNode(true);
clone.setAttribute("id", "tv-" + i)
clone.setAttribute("data-channel", 0)
clone.style.backgroundColor = tvs[i].channels[0]
container.appendChild(clone)
}
const buttons = document.getElementsByClassName("channel-btn")
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', () => changeChannel(i), false);
}
<div id="container"></div>
<div id="tv-template" style="display: none;">
<div class="tv" style="width: 70px; height: 70px; margin-bottom: 20px;">
<button class="channel-btn">next</button>
</div>
</div>

How to create a Docking Panel (in the newer version of autodesk forge viewer)

Note: I have updated my previous code with the suggestions provided below in the answer.
After following the suggestion, I've found that the docking panel is added to the DOM. But not being displayed(even though z-index is set to 2)
This is what I have tried so far. Also, find the screenshot of the console result below.
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1, user-scalable=no" />
<meta charset="utf-8">
<link rel="stylesheet" href="https://developer.api.autodesk.com/modelderivative/v2/viewers/7.*/style.min.css" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://developer.api.autodesk.com/modelderivative/v2/viewers/7.*/viewer3D.min.js"></script>
<style>
body {
margin: 0;
}
#forgeViewer {
width: 100%;
height: 100%;
margin: 0;
background-color: #F0F8FF;
}
</style>
</head>
<body>
<div id="forgeViewer"></div>
</body>
<script>
var viewer;
var options = {
env: 'AutodeskProduction',
api: 'derivativeV2', // for models uploaded to EMEA change this option to 'derivativeV2_EU'
getAccessToken: function(onTokenReady) {
var token = 'access token here';
var timeInSeconds = 3600; // Use value provided by Forge Authentication (OAuth) API
onTokenReady(token, timeInSeconds);
}
};
SimplePanel = function(parentContainer, id, title, content, x, y)
{
this.content = content;
Autodesk.Viewing.UI.DockingPanel.call(this, parentContainer, id, title,{shadow:false});
// Auto-fit to the content and don't allow resize. Position at the coordinates given.
//
this.container.style.height = "150px";
this.container.style.width = "450px";
this.container.style.resize = "auto";
this.container.style.left = x + "px";
this.container.style.top = y + "px";
this.container.style.zIndex = 2;
};
SimplePanel.prototype = Object.create(Autodesk.Viewing.UI.DockingPanel.prototype);
SimplePanel.prototype.constructor = SimplePanel;
SimplePanel.prototype.initialize = function()
{
this.title = this.createTitleBar(this.titleLabel || this.container.id);
this.container.appendChild(this.title);
this.container.appendChild(this.content);
this.initializeMoveHandlers(this.container);
this.closer = this.createCloseButton();
this.title.appendChild(this.closer);
var op = {left:false,heightAdjustment:45,marginTop:0};
this.scrollcontainer = this.createScrollContainer(op);
var html = [
'<div class="uicomponent-panel-controls-container">',
'<div class="panel panel-default">',
'<table class="table table-hover table-responsive" id = "clashresultstable">',
'<thead>',
'<th>Name</th><th>Status</th><th>Found</th><th>Approved By</th><th>Description</th>',
'</thead>',
'<tbody>',
'<tr><td>test</td><td>test</td><td>test</td><td>test</td><td>test</td></tr>',
'<tr><td>test</td><td>test</td><td>test</td><td>test</td><td>test</td></tr>',
'<tr><td>test</td><td>test</td><td>test</td><td>test</td><td>test</td></tr>',
'<tr><td>test</td><td>test</td><td>test</td><td>test</td><td>test</td></tr>',
'<tr><td>test</td><td>test</td><td>test</td><td>test</td><td>test</td></tr>',
'<tr><td>test</td><td>test</td><td>test</td><td>test</td><td>test</td></tr>',
'<tr><td>test</td><td>test</td><td>test</td><td>test</td><td>test</td></tr>',
'</tbody>',
'</table>',
'</div>',
'</div>'
].join('\n');
$(this.scrollContainer).append(html);
this.initializeMoveHandlers(this.title);
this.initializeCloseHandler(this.closer);
};
Autodesk.Viewing.Initializer(options, function() {
var htmlDiv = document.getElementById('forgeViewer');
viewer = new Autodesk.Viewing.GuiViewer3D(htmlDiv);
var startedCode = viewer.start();
if (startedCode > 0) {
console.error('Failed to create a Viewer: WebGL not supported.');
return;
}
console.log('Initialization complete, loading a model next...');
});
var documentId = 'urn:urn here';
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
function onDocumentLoadSuccess(viewerDocument) {
var defaultModel = viewerDocument.getRoot().getDefaultGeometry();
viewer.loadDocumentNode(viewerDocument, defaultModel);
viewer.addEventListener( Autodesk.Viewing.SELECTION_CHANGED_EVENT, event=>{
//console.log(viewer.model.getData());
console.log(viewer.model.getDocumentNode());
// console.log(SimplePanel.container)
viewer.getPropertyPanel(true).setVisible(true)
var content = document.createElement('div');
var mypanel = new SimplePanel(NOP_VIEWER.container,'mypanel','My Panel',content);
mypanel.setVisible(true);
})
}
function onDocumentLoadFailure() {
console.error('Failed fetching Forge manifest');
}
</script>
</html>```[![console output for the dom][1]][1]
[![DOM screenshot on console][1]][1]
[1]: https://i.stack.imgur.com/Lp1rm.png
You'd need to explicitly call Autodesk.Viewing.UI.DockingPanel.setVisible(true) to make the panel visible and put in the desired position with the correct z-index ahead of overlapping elements in the viewport as well:
SimplePanel.container.style.width = width
SimplePanel.container.style.height = height
SimplePanel.container.style.left = left
SimplePanel.container.style.top = top
SimplePanel.container.style.z-index = 2 // or another value to suit the rest of your UI
SimplePanel.setVisible(true)
Otherwise you'd notice it's already present in the DOMtree with display set to none or either rendered outside of the visible viewport (positioned at top:0,left:0 etc) or behind(blocked by) other elements ...
If the panel still does not appear try to look for relevant console output esp. error messages when you trigger the selection event and check if the panel is already rendered to the DOMtree in the browser's developer tool but somehow still not visible

How to close a docking panel when opening a new instance in the autodesk forge viewer api?

I have been displaying data attached to a few nodes in the viewer using a custom docking panel. I have attached the listener event on the click of those nodes and instantiating a new docking panel instance.
It works fine. New custom panel get's displayed every time I click on a node. There is a close handler attached to the close button which closes the panel.
But, how can I close the existing panel before opening a new one? I tried to initialize the viewer with initializeCloseHandler so that wherever clicked the opened docking panel closes. But it's not working. I am unable to get the viewer instance there.
Now both instances get added one above another. I am attaching a screenshot of it for reference - https://i.stack.imgur.com/lT5Y1.png
How can I achieve this? This is what I have tried so far,
Sample code:
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1, user-scalable=no" />
<meta charset="utf-8">
<link rel="stylesheet" href="https://developer.api.autodesk.com/modelderivative/v2/viewers/7.*/style.min.css" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://developer.api.autodesk.com/modelderivative/v2/viewers/7.*/viewer3D.min.js"></script>
<style>
body {
margin: 0;
}
#forgeViewer {
width: 100%;
height: 100%;
margin: 0;
background-color: #F0F8FF;
}
</style>
</head>
<body>
<div id="forgeViewer"></div>
</body>
<script>
var viewer;
var options = {
env: 'AutodeskProduction',
api: 'derivativeV2', // for models uploaded to EMEA change this option to 'derivativeV2_EU'
getAccessToken: function(onTokenReady) {
var token = 'access token here';
var timeInSeconds = 3600; // Use value provided by Forge Authentication (OAuth) API
onTokenReady(token, timeInSeconds);
}
};
SimplePanel = function(parentContainer, id, title, content, x, y)
{
this.content = content;
Autodesk.Viewing.UI.DockingPanel.call(this, parentContainer, id, title,{shadow:false});
// Auto-fit to the content and don't allow resize. Position at the coordinates given.
//
this.container.style.height = "250px";
this.container.style.width = "450px";
this.container.style.resize = "auto";
this.container.style.left = x + "px";
this.container.style.top = y + "px";
this.container.style.zIndex = 2;
};
SimplePanel.prototype = Object.create(Autodesk.Viewing.UI.DockingPanel.prototype);
SimplePanel.prototype.constructor = SimplePanel;
SimplePanel.prototype.initialize = function()
{
this.title = this.createTitleBar(this.titleLabel || this.container.id);
this.container.appendChild(this.title);
this.container.appendChild(this.content);
this.initializeMoveHandlers(this.container);
this.closer = document.createElement("span");
this.closer = this.createCloseButton();
this.initializeCloseHandler(this.closer);
this.container.appendChild(this.closer);
var op = {left:false,heightAdjustment:45,marginTop:0};
this.scrollcontainer = this.createScrollContainer(op);
// console.log("id - "+viewer.model.getFragmentList().fragments.fragId2dbId);
console.log(viewer.getSelection());
var id = viewer.getSelection();
var dataItem;
var data = [
{
id:"2648",
name:"Chiller",
temp:"300 deg",
serviceReq:true,
reservations:"3"
},
{
id:"2228",
name:"Door",
temp:"150 deg",
serviceReq:false,
reservations:"4"
},
{
id:"2198",
name:"Cooler",
temp:"400 deg",
serviceReq:true,
reservations:"2"
}
]
data.forEach(item => {
if(item.id == id){
dataItem = item;
}
})
var html = [
'<div class="uicomponent-panel-controls-container">',
'<div class="panel panel-default">',
'<table class="table table-hover table-responsive" id = "clashresultstable">',
'<thead>',
'<th>Key</th><th>Value</th>',
'</thead>',
'<tbody>',
'<tr><td>ID</td><td>'+dataItem.id+'</td></tr>',
'<tr><td>Name</td><td>'+dataItem.name+'</td></tr>',
'<tr><td>Temperature</td><td>'+dataItem.temp+'</td></tr>',
'<tr><td>Service Requests</td><td>'+dataItem.serviceReq+'</td></tr>',
'<tr><td>Reservations</td><td>'+dataItem.reservations+'</td></tr>',
'</tbody>',
'</table>',
'</div>',
'</div>'
].join('\n');
$(this.scrollContainer).append(html);
this.initializeMoveHandlers(this.title);
};
Autodesk.Viewing.Initializer(options, function() {
var htmlDiv = document.getElementById('forgeViewer');
viewer = new Autodesk.Viewing.GuiViewer3D(htmlDiv);
var startedCode = viewer.start();
if (startedCode > 0) {
console.error('Failed to create a Viewer: WebGL not supported.');
return;
}
console.log('Initialization complete, loading a model next...');
});
var documentId = 'urn:(urn)';
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
function onDocumentLoadSuccess(viewerDocument) {
var defaultModel = viewerDocument.getRoot().getDefaultGeometry();
viewer.loadDocumentNode(viewerDocument, defaultModel);
viewer.addEventListener( Autodesk.Viewing.SELECTION_CHANGED_EVENT, event=>{
var content = document.createElement('div');
var mypanel = new SimplePanel(NOP_VIEWER.container,'mypanel','My Panel',content,20,20);
mypanel.setVisible(true);
})
}
// function closer(){ -- tried to attach this handler to the viewer instance,but didn't work
// SimplePanel.setVisible(false);
// }
function onDocumentLoadFailure() {
console.error('Failed fetching Forge manifest');
}
</script>
</html>````
[1]: https://i.stack.imgur.com/lT5Y1.png
I would advise you to use a viewer extension to manage your panel in order to reuse the same panel instance. Here are some examples for you:
https://github.com/yiskang/forge-au-sample/blob/master/properties/scripts/AdnPropsPanel.js
https://github.com/yiskang/forge-au-sample/blob/master/model-structure/scripts/AdnStructurePanel.js
If you don't want to implement an extension, you may store the mypanel variable somewhere, and use if statement to destroy the old panel before creating a new one.
var mypanel = null;
// Other code snippet
viewer.addEventListener( Autodesk.Viewing.SELECTION_CHANGED_EVENT, event=> {
if( mypanel != null ) {
//NOP_VIEWER.container.removeChild( mypanel.container );
mypanel.uninitialize();
mypanel = null;
}
var content = document.createElement('div');
mypanel = new SimplePanel(NOP_VIEWER.container,'mypanel','My Panel',content,20,20);
mypanel.setVisible( true );
})
Hope it helps!

How to get info from background_page to popup?

I'm following the official Chrome Extension tutorial called Chritter where they fetch tweets from Twitter and place them into the extension. I'm trying to do similar except im trying to fetch items from an xml file.
My XML
<xml>
<item>
<title>Title 1</title>
<description>Description 1</description>
<duration>55:00</duration>
<published>28/01/2011</published>
</item>
<item>
<title>Title 2</title>
<description>Description 2</description>
<duration>55:00</duration>
<published>28/01/2011</published>
</item>
</xml>
background.html
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var fetchFreq = 30000; // how often we fetch new items (30s)
var req; // request object
var unreadCount = 0; // how many unread items we have
var items; // all currently fetched items
getItems();
//setInterval(getItems, fetchFreq);
function getItems(){
req = new XMLHttpRequest();
req.open("GET", "http://urltoxml.com/xmlfile.xml", false);
req.onload = processItems;
req.send();
}
function processItems(){
xmlDoc = req.responseXML;
items = xmlDoc.getElementsByTagName("item");
unreadCount += items.length;
if (unreadCount > 0) {
chrome.browserAction.setBadgeBackgroundColor({
color: [255, 0, 0, 255]
});
chrome.browserAction.setBadgeText({text: '' + unreadCount});
}
items = xmlDoc.concat(items);
}
</script>
</head>
</html>
I don't know how to get the fetched items from the background.html and displayed onto the popup.html ?
popup.html
<html>
<head>
<link rel="stylesheet" href="popup.css" />
<script src="util.js"></script>
<script>
var bg; // background page
// timeline attributes
var timeline;
var template;
var title;
var link;
var description;
onload = setTimeout(init, 0); // workaround for http://crbug.com/24467
// initialize timeline template
function init() {
chrome.browserAction.setBadgeText({text: ''});
bg = chrome.extension.getBackgroundPage();
bg.unreadCount = 0;
timeline = document.getElementById('timeline');
template = xpath('//ol[#id="template"]/li', document);
title = xpath('//div[#class="text"]/span', title);
content = xpath('//div[#class="text"]/span', template);
update();
}
function update(){
// how to do this ?
// See Chritter example below with JSON,
// except i want to it with xml ?
}
</script>
</head>
<body>
<div id="body">
<ol id="timeline" />
</div>
<ol id="template">
<li>
<div class="text">
<a></a>
<span></span>
</div>
<div class="clear"></div>
</li>
</ol>
</body>
</html>
The way the Chritter extension does it only seems to work with JSON. Here is how they do it:
// update display
function update() {
var user;
var url;
var item;
for (var i in bg.tweets) {
user = bg.tweets[i].user;
url = 'http://twitter.com/' + user.screen_name;
// thumbnail
link.title = user.name;
link.href = openInNewTab(url);
image.src = user.profile_image_url;
image.alt = user.name;
// text
author.href = openInNewTab(url);
author.innerHTML = user.name;
content.innerHTML = linkify(bg.tweets[i].text);
// copy node and update
item = template.cloneNode(true);
timeline.appendChild(item);
}
}
Chritter background.html
<html>
<head>
<script type="text/javascript">
var fetchFreq = 30000; // how often we fetch new tweets (30s)
var req; // request object
var unreadCount = 0; // how many unread tweets we have
var tweets; // all currently fetched tweets
getTweets();
setInterval(getTweets, fetchFreq);
// fetch timeline from server
function getTweets() {
req = new XMLHttpRequest();
req.open('GET', 'http://twitter.com/statuses/public_timeline.json');
req.onload = processTweets;
req.send();
}
// process new batch of tweets
function processTweets() {
var res = JSON.parse(req.responseText);
unreadCount += res.length;
if (unreadCount > 0) {
chrome.browserAction.setBadgeBackgroundColor({
color: [255, 0, 0, 255]
});
chrome.browserAction.setBadgeText({text: '' + unreadCount});
}
tweets = res.concat(tweets);
}
</script>
</head>
</html>
Any help much appreciated! Thanks!
If you want to access items var from a background page then:
var items = chrome.extension.getBackgroundPage().items;
I am not sure what the exact question is, but the general practice is to store the data from background page into localstorage and then access this data from the popup page.
http://www.rajdeepd.com/articles/chrome/localstrg/LocalStorageSample.htm