How to use loaded data from a csv file in JavaScript? - javascript

H! Guys
First of all, excuse me for my bad english (I'm working on it). Second: I don't know anything about JavaScript and copy this codes piece by peace. So be patient and listen to my situation please.
I have a svg map and when you click on each sectoin, a box will appear and show the region's name and region's evaluation. I already solve the region's name part with:
for (var i = 0; i < regions.length; i++){
.... some line codes ....
$infobox.find('.infobox_title').text(this.data('region_name'));
.... some line codes ....
Now I want to grab Evaluation's value from a csv file that loads to page using:
function loadFile(event) {
alasql('SELECT * FROM FILE(?,{headers:true})',[event],function(data){
var myseries = [];
Object.keys(data[0]).forEach(function(key){
var ds = data.map(function(d){ return +d[key];});
myseries.push({name:key,data:ds});
});
});
}
I'm sure the data is loaded to page, cuz I checked in console log:
console.log(key);
console.log(ds);
And my csv file is something like this:
regions,evaluation
1,90
2,80
...
22,70
Pleas tell me How can I grab the evaluation numbers that loaded to the page and replace it in place of "Evaluation's place" ???
Take a look at snapshot for clearity:

You can try this code to put labels on top of image.
First, prepare the image with the map in HTML and cover it with container DIV element:
<div id="container">
<img src="map.jpg" style="position:absolute; top:0px; left:0px;"/>
</div>
Then create the new label element, add style properties (position, content, color, etc.) and append it to container on top of it (look at the "position:absolute" style element):
var container = document.getElementById('container');
// Create new element dinamically
var lb = document.createElement('div');
lb.innerHTML = '<b>'+d.regionid+'</b><br/>'+d.evaluation;
lb.style.position = "absolute";
lb.style.left = regions[d.regionid-1].x+"px";
lb.style.top = regions[d.regionid-1].y+"px";
// Append new element to container
container.appendChild(lb);
See the working snipped below or in jsFiddle
Comments:
I did not include the reading CSV code in the example (because you already loaded it).
The example does not use d3.js library.
Please, comment if these conditions are important.
var data = [
{regionid:1,evaluation:90},
{regionid:2,evaluation:80},
{regionid:3,evaluation:70},
{regionid:4,evaluation:60},
{regionid:5,evaluation:50},
{regionid:6,evaluation:40},
{regionid:7,evaluation:30},
];
var regions = [
{x:110,y:100},
{x:220,y:100},
{x:250,y:180},
{x:250,y:230},
{x:290,y:220},
{x:150,y:160},
{x:350,y:180},
];
var container = document.getElementById('container');
for(var i=0; i<data.length; i++) {
var d = data[i];
var lb = document.createElement('div');
lb.innerHTML = '<b>'+d.regionid+'</b><br/>'+d.evaluation;
lb.style.position = "absolute";
lb.style.left = regions[d.regionid-1].x+"px";
lb.style.top = regions[d.regionid-1].y+"px";
lb.style.backgroundColor = "white";
lb.style.textAlign = "center";
container.appendChild(lb);
};
<div id="container">
<img src="https://pbs.twimg.com/media/B8woY_DCMAEojTy.jpg" style="position:absolute; top:0px; left:0px;"/>
</div>

Related

How to extract all html text excluding what's inside the script tag?

For a project I want to create a variable that stores all the text within the html, so pretty much everything between tags, titles, paragraphs, everything visible for a user on a webpage. However I don't want my javascript code that's between the script tag to show up in this output too.
I was trying with something like this:
var content = $("html").remove("script").text()
But this is not working.
Here it is:
First use this:
var r = document.getElementsByTagName('script');
for (var i = (r.length-1); i >= 0; i--) {
if(r[i].getAttribute('id') != 'a'){
r[i].parentNode.removeChild(r[i]);
}
}
And then:
var txt = document.body.innerText;
OR
var txt = $('body').text();
var contentDiv = $('<div/>', {
html: $('body').clone()
});
contentDiv.find('script').remove()
return contentDiv.text()

Get bootstrap accordion height

I'm trying to use HTML2Canvas with jsPDF to save some accordions to the pdf. Accordions are created dynamically with javascript and i'm trying to get their height to save them to pdf (i need to split the page at some point and save them in separate images because they're way too big). I've gathered all the accordions with their classname:
function gatherAccordions(){
//Launched on button click
var accordionArr = document.getElementsByClassName("akkordion");
for (var i = 0; i<accordionArr.length;i++){
console.log(accordionArr[i]);
console.log(accordionArr[i].clientHeight); //returns 0
}
}
Edit: as i read a bit more i got that .clientHeight will return 0 in case height is not set in CSS. I decided to try the jQuery approach which was highly suggested. Although it returned me -2 (which obviously can't be the right height).
function gatherAccordions(){
var accordionArr = document.getElementsByClassName("akkordion");
for (var i = 0; i<accordionArr.length;i++){
console.log(accordionArr[i]);
console.log($("#"+accordionArr[i].id).height()); //returns -2
}
}
Any ideas how could I approach this thing? I have to note that the accordions (as you can see from code below) are not the bottom elements of the accordion tree, there are several divs and other stuff below it. If i gave .height() to accordionBody and accordionhead separately i did recieve -20 and -31 as a result height, which also sounds weird (being negative). Also, when i added elements to the accordion body then the height of body did not increase although visually i can clearly tell that it did.
This builds the accordions:
/*
#Builds the head of accordion which contains main stats
*/
function buildAccordionHead(player){
//player has attributes: coef, ratio, pos, hasplayed, name, points
//This is the panel that holds the player main information (coef,name,pos etc)
var accordionHead = document.createElement("div");
accordionHead.className = "panel-heading";
accordionHead.dataset.parent = "#accordion";
accordionHead.dataset.toggle = "collapse";
accordionHead.setAttribute('href', "#id_"+player.pos);
//This is the container for positioning items
var container = document.createElement("div");
container.className = "container-fluid";
//Create playerrow (FN06)
var upper_row = rowCreate("KOHT","","K","S","P",true);
var playerRow = rowCreate(player.pos,player.name,player.coef,player.ratio,player.score,false);
//Add row(s) to the children of container
container.appendChild(upper_row);
container.appendChild(playerRow);
//Add container to the children of accordion head
accordionHead.appendChild(container);
return accordionHead;
}
/*
Builds the body of the accordion which contains history
*/
function buildAccordionBody(player,round){
//moving inside out!
//generates container-fluid element with a rows inside
if (even){
var containerfluid = historyRowEven(player);
}
else{
var containerfluid = historyRowOdd(player,round);
}
var bodyel = document.createElement("div");
bodyel.className = "panel-body";
bodyel.appendChild(containerfluid);
var collapser = document.createElement("div");
collapser.id = "id_"+player.pos;
collapser.className = "panel-collapse collapse";
collapser.appendChild(bodyel);
return collapser;
}
/*
The main builder function!
*/
function buildAccordion(player,round){
//This is outer panel
var accordionPanel = document.createElement("div");
accordionPanel.className = "panel panel-default akkordion";
var accordionHeading = buildAccordionHead(player);
var accordionBody = buildAccordionBody(player,round);
//Add accordion head to the children of accordion-panel
accordionPanel.appendChild(accordionHeading);
accordionPanel.appendChild(accordionBody);
accordionPanel.id = "collapser_id_"+player.pos;
//Add accordion-panel to the children of div with accordion
var mainElement = document.getElementById("accordion");
mainElement.appendChild(accordionPanel);
}

Inserting CSS-linked HTML in HTML page code via JS

I do not have access to the HTML of the pages (they are program-built dynamically).
I do have access to the JS page it is linked to.
For example I can do somethin like this and it works:
window.onload=function(){
var output = document.getElementById('main_co');
var i=1;
var val="";
while(i<=1)
{ if(!document.getElementById('timedrpact01'+i))
{
var ele = document.createElement("div"); ele.setAttribute("id","timedrpact01"+i);
ele.setAttribute("class","inner");
ele.innerHTML=" Hi there!" ;
output.appendChild(ele);
I would like to use this basis insert a button that would allow to switch from one CSS set (there are several files invoked) to another _another path.
Many thanks
The external stylesheets are referenced using link, as in:
<link rel="stylesheet" href="http://example.com/path-to-css">
So, get hold of the appropriate link element using:
var css = document.getElementsByTagName("link")[0];
Here, we got hold of the first link available by specifying the [0] index.
Then, overwrite the href attribute to point it to the new path.
css.setAttribute("href", "http://example.com/path-to-css");
window.onload=function(){
var output = document.getElementById('main_co');
var i=1;
var val="";
//switch all the href's to another path
var switchStyleSheet = function() {
var links = document.getElementsByTagName("link");
for(var i=0; lkC = links.length; i < lkC; i++)
links[0].href = links[0].href.replace('path_to_file', '_path_to_file');
};
while(i<=1) //while is not required here, if i is 1
{
if(!document.getElementById('timedrpact01'+i)) {
var ele = document.createElement("div"); ele.setAttribute("id","timedrpact01"+i);
ele.setAttribute("class","inner");
ele.innerHTML=" Hi there!" ;
var button = document.createElement('button');
if(button.addEventListener) {
button.addEventListener('click', switchStyleSheet);
}
else {
button.attachEvent('click', switchStyleSheet);
}
output.appendChild(button);
output.appendChild(ele);
}
}
}

variable is null when pulling from a div

Sorry in advance for the extremely banal question, I'm positive I am missing something extremely simple. Without further adieu;
I'm getting a type error when I try to pull a block of text, and a button, from a div in my HTML. The div has an id that I am accurately referencing. For oversight, I am attempting to retrieve the text, apply coloring to each word (cycling through red, blue, and green), and replace the original text with my colored text. It works fine in JSFiddle, but I cannot get the data to retrieve in espresso - transcribeText is null.
var transcribeText = document.getElementById("divideTranscript");
transcribeText.onclick = function() {
var words = document.getElementById("transcriptText");
var textArray = words.innerHTML.split(" ");
var count = 0;
var colorArr = ["red", "blue", "green"];
var newWords = document.createElement("div");
for(var i = 0; i < textArray.length; i++){
var item = textArray[i];
var newSpan = document.createElement("span");
var newText = document.createTextNode(item);
var dotNode = document.createTextNode(" ");
newSpan.className = colorArr[count % 3];
newSpan.id = "word"+i;
newSpan.appendChild(newText);
newSpan.appendChild(dotNode);
count++;
};
words.parentNode.replaceChild(newWords, words);
}
<div id="transcriptText"> It’s that time of year when you clean out your
closets, dust off shelves, and spruce up your floors. Once you’ve taken
care of the dust and dirt, what about some digital cleaning? Going
through all your files and computers may seem like a daunting task, but
we found ways to make the process fairly painless.</div>
<br>
<div id="divideTranscript" class="button"> Transform the
Transcript! </div>
Your problem is that the javascript runs before the HTML exists, therefore, you cannot get any ids. There are several ways around this. First is my favorite:
window.onload = function name() {
//code to be excuted
}
The function will be called after HTML has loaded. body.onload = function name() also works.
The second method (no pun intended haha) is to put the script tag at the end of the body tag.
<body>
<script></script>
</body>
Personally, I use the first one more commonly because I have a template I religiously use, and I don't like moving tags around. That's just me, whatever works for you! Hope this Helps!

how to create drop down list in java script?

For example if i have a list item like all,a,b,c,d. if i click all means it should not allow to choose other items, if i am not choosing all means it should allow to choose mulitle item from list
<script type="text/javascript">
var creatLimit = 5;
var fCount = 0;
function addFileElement()
{
if(fCount < creatLimit)
{
var fObject = document.getElementById("name");
var addButton = document.createElement("select");
addButton.type = "select";
addButton.name = "List["+fCount+"]";
addButton.setAttribute("class", "normal");
addButton.style.width = "250px";
addButton.onkeydown = function(){
blur();
};
var o2 = document.createElement("br");
var o3 = document.createElement("br");
fObject.appendChild(addButton);
fObject.appendChild(o2);
fObject.appendChild(o3);
fCount++;
}
}
</script>
You are confusing your terminologies here slightly - JavaScript itself doesn't show any UI, it is the HTML (or the XUL or something completely different) which shows the UI.
Assuming that you are talking about html, the way to create a drop down list is simply to write the corresponding html for the drop down list to wherever it is in the document that you wish the drop down list to be placed, for example:
<div id="myDiv"></div>
<script type="text/javascript">
myDiv = document.getElementById("myDiv");
myDiv.innerHtml = "<select><option>a</option><option>b</option><option>c</option><option>d</option>";
</script>
Most likely you will be dynamically writing the HTML based on an existing list of items, but I don't want to go into that in too much detail because that will completely depend on your specific requirements and because jQuery will make this a lot easier.
EDIT: Typo fix in variable names.

Categories