How do I fix weather-info not showing - javascript

I've been trying to add weather-info to my website using api but cant get it to work, don't really know what the problem is. The temperature of a preset location, which is all i need to display, just doesn't show up.
I tried getting elementByID from a div in my HTML-code but this didnt work so now I'm using a table and trying to insert it into the table.
function addWeather(JSONdata) {
/* let temperatureNow = document.getElementById("temp");*/
let table1 = document.getElementById("table");
let rowNr = 1;
let today = new Date();
let time = today.getHours();
for (let i = 0; i < JSONdata.length; i++) {
let tempDate = new Date(JSONdata.timeSeries[i].validTime);
let hoursTemp = tempDate.getHours();
let row = table1.insertRow(rowNr);
let cell1 = row.insertCell(0);
if (time == hoursTemp
) {
/*temperatureNow == JSONdata.timeSeries[i].parameters[1].values[0];*/
for (let index = 0; index < JSONdata.timeSeries[i].parameters.length; index++) {
if (JSONdata.timeSeries[i].parameters[index].name == "t") {
console.log(JSONdata.timeSeries[i])
cell1.innerHTML = JSONdata.timeSeries[i].parameters[index].values + '℃';
}
}
}
}
}

Related

Update Array when new elements are displayed on webpage

I'm working on a chrome extension where I need to gather the total number of books in a library.
The code below works fine, however, the page where I'm getting the data only loads half of the books at once until you scroll down further and the array doesn't update accordingly.
Is there a way to automatically update the array to keep up with the changes?
let list = document.querySelectorAll("ul > li");
let numBooks = [];
for (let i = 0; i < list.length; i++) {
numBooks.push(i + 1);
}
console.log(numBooks);
// Variables
let list = document.querySelectorAll("ul > li");
let mlist = document.querySelector("ul");
let numBooks = [];
// Push books to array
for (let i = 0; i < list.length; i++) {
numBooks.push(i + 1);
}
// Observe changes
const observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if (mutation.addedNodes.length) {
// Create Element: Book Count
let url = "myurl";
let nBooks = numBooks.length / 10;
let nChanges = mutation.addedNodes.length - 1;
if (url == window.location.href) {
let el = document.createElement("span");
el.innerHTML = nBooks + nChanges;
let par = document.getElementsByTagName("h2")[0];
par.appendChild(el);
}
}
});
});
observer.observe(mlist, {
childList: true,
});

Create a random array to compare between the users array and flashes on a simon says game

i'm bulding a simon game as a student work project in school. i bulit the "card game "Dynamically by entering cell's to a table in pure js now i would want to make the "card game " to flash in a Random Sequence so i had created a random var and add a classList to evry random but here is the problem
1) i would want to creat a random array to compare between the users array when playing and it seems that i cant do a classLiss.add() to it
2)i would want to "flash" the "cards game" that evry time it will flash once and NOT at the same time (and also at the first turn it will flashh once and at the second turn it will flash Twice {not on the same time.exc}) i did use a setTimeout function to remove classList
Here is the code for "card display" and random function:
function cards(user) {
userchioce = parseInt(user.value);
if (userchioce == 4) {
var table = document.getElementById("mytable");
document.getElementById("mytable").innerHTML = "";
for (var i = 0; i < 2; i++) {
var row = table.insertRow(0);
for (var j = 0; j < 2; j++) {
var cell = row.insertCell(-1);
}
}
var t = document.getElementById("mytable");
var idnum = 0;
counter = 0;
for (var r = 0; r < t.rows.length; r++) { //luop at length of rows
for (var c = 0; c < t.rows[r].cells.length; c++) { //luop at length of rows and cells
t.rows[r].cells[c].style.backgroundColor = colorarry[counter];
t.rows[r].cells[c].innerHTML = colorarry1[counter];
t.rows[r].cells[c].setAttribute("class", "td1");
t.rows[r].cells[c].setAttribute("id", "tdd" + idnum++);
counter++;
}
}
}
counter = 0;//end of if 4
function getrandom(rnd) {
rnd = Math.floor(Math.random() * userchioce);
var id = "tdd";
var fullid = id + rnd;
var dispaly = document.getElementById(fullid);
dispaly.classList.add("flash");
{
setTimeout(function () {
dispaly.classList.remove("flash");
}, 850);
}
}
Alright, let's clean up a little first. You are creating looping to create the cells, then looping again to modify them, you should just modify them right away.
if (userchioce == 4) {
var table = document.getElementById("mytable");
document.getElementById("mytable").innerHTML = "";
var idnum = 0;
for (var i = 0; i < 2; i++) {
var row = table.insertRow(0);
for (var j = 0; j < 2; j++) {
var cell = row.insertCell(-1);
cell.style.backgroundColor = colorarry[idnum];
cell.innerHTML = colorarry1[idnum];
cell.setAttribute("class", "td1");
cell.setAttribute("id", "tdd" + idnum++);
}
}
}
I've also removed the counter variable in favour to the idnum variable. They were both defined at 0 at the same place, and also incremented at the same pace...
You do not get to display the lights one after the other because you only do it once. There should be a place where you keep track of the previous randoms.
var moves = [];
function newTurn() {
var rnd = Math.floor(Math.random() * userchioce);
// Add the new random to the moves history.
moves.push(rnd);
//create a copy, we'll be playing with it.
var movesToShow = moves.slice();
showMove();
}
function showMove(moveList){
//Remove first value of the list of moves and use it to show.
var move = moveList.shift();
var id = "tdd";
var fullid = id + move;
var display= document.getElementById(fullid);
display.classList.add("flash");
//Wait a little before removing the hightlight.
setTimeout(function () {
display.classList.remove("flash");
if(moveList.length>0){
//There are more moves, wait just a little
setTimeout(function(){
//Display a new move.
showMove(moveList);
},100);
}
}, 850);
}
// call this to start a new turn.
newTurn();
Also, I would like to urge you to correct all the typos in your script. "dispaly","userchioce" this will make things very hard for you to follow.

How to clear previous api result when a new query is made

So I'm using https://calendarific.com api and am trying to make an "app" where you can click on your country and it returns the holidays based on the current month. It kinda works except when I click on one country and then another the previous countries result stays on the top and the new country's holidays get put to the bottom of the page.
How can I remove previous results when a new one is made?
Javascript (sorry if it's a bit messy):
countrySelect.addEventListener('click', function() {
// Api url
let url = `https://calendarific.com/api/v2/holidays?&api_key=a7167178ffb6d2d7d8d9c1e05d98eab926f595e9&country=${buttonValue}&year=2020`;
fetch(url)
.then(res => res.json())
.then(data => {
// Filters holiday's to the current month
var currentMonthHolidays = data.response.holidays.filter(holiday => {
var holidayDate = new Date(holiday.date.iso);
var holidayMonth = holidayDate.getMonth();
var date = new Date();
var currentMonth = date.getMonth();
return currentMonth === holidayMonth;
})
// Build holiday table
function buildTable(data){
let table = document.getElementById('resultTable');
let col = [];
// Get the index of the api titles
for (let i = 0; i < currentMonthHolidays.length; i++) {
for (let key in currentMonthHolidays[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
console.log(col)
}
//Create table header row using the extracted headers above.
let tr = table.insertRow(-1); // table row.
for (let i = 0; i < col.length; i++) {
let th = document.createElement("th"); // table header.
th.innerHTML = col[i];
tr.appendChild(th);
}
// add json data to the table as rows.
for (let i = 0; i < currentMonthHolidays.length; i++) {
tr = table.insertRow(-1);
for (let j = 0; j < col.length; j++) {
let tabCell = tr.insertCell(-1);
tabCell.innerHTML = currentMonthHolidays[i][col[j]];
}
}
}
buildTable(currentMonthHolidays);
console.log(currentMonthHolidays);
//handles error
}, networkError => {
alert(networkError)
})
})
If you are only concerned about just getting new data on top,
in your code just add :
table.removeChild(table.tBodies[0]);
which becomes :-
countrySelect.addEventListener('click', function() {
// Api url
let url = `https://calendarific.com/api/v2/holidays?&api_key=a7167178ffb6d2d7d8d9c1e05d98eab926f595e9&country=${buttonValue}&year=2020`;
fetch(url)
.then(res => res.json())
.then(data => {
// Filters holiday's to the current month
var currentMonthHolidays = data.response.holidays.filter(holiday => {
var holidayDate = new Date(holiday.date.iso);
var holidayMonth = holidayDate.getMonth();
var date = new Date();
var currentMonth = date.getMonth();
return currentMonth === holidayMonth;
})
// Build holiday table
function buildTable(data){
let table = document.getElementById('resultTable');
let col = [];
// Get the index of the api titles
for (let i = 0; i < currentMonthHolidays.length; i++) {
for (let key in currentMonthHolidays[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
console.log(col)
}
//Create table header row using the extracted headers above.
let tr = table.insertRow(-1); // table row.
for (let i = 0; i < col.length; i++) {
let th = document.createElement("th"); // table header.
th.innerHTML = col[i];
tr.appendChild(th);
}
/*
since all <tr> are wrapped inside <tbody>, so just remove the old one and you are good to go
*/
table.removeChild(table.tBodies[0]);
// add json data to the table as rows.
for (let i = 0; i < currentMonthHolidays.length; i++) {
tr = table.insertRow(-1);
for (let j = 0; j < col.length; j++) {
let tabCell = tr.insertCell(-1);
tabCell.innerHTML = currentMonthHolidays[i][col[j]];
}
}
}
buildTable(currentMonthHolidays);
console.log(currentMonthHolidays);
//handles error
}, networkError => {
alert(networkError)
})
})

Setting a value in a drop down with Google Sheets using a script

I need to figure out a way to set a drop down value based on if another cell in the same row has a value. So for instance if D2 has a value other than '' or null; H2 needs to be set to "New Issue". The answers found in another similar post don't actually work with this since I am using formRedirector. Things got really weird last time. I tried to delete the earlier post but couldn't.
I have some of the logic figured out, but the issue is that what I have now writes "New issue" to H3 and below. Here is what I have so far:
var NEW_ISSUE = 'New Issue';
function defaultValue() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
var numRows = 900;
var dataRange = sheet.getRange(startRow, 4, numRows);
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var default_status = row[7];
if (default_status != NEW_ISSUE && row == '') {
sheet.getRange(startRow + i, 8).setValue(NEW_ISSUE);
}
}
}
I have a feeling somewhere in the if statement I am messing up somewhere.
This solved the issue, thank you
var NEW_ISSUE ='New Issue';
var row;
var default_status;
function defaultValue() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 1;
var numRows = 900;
var dataRange = sheet.getRange(startRow, 4, numRows);
var data = dataRange.getValues();
var statusRange = sheet.getRange(startRow,8,numRows);
var status = statusRange.getValues();
for (var i = 0; data[i] != ''; ++i)
{
if (status[i] == '')
{
sheet.getRange(i+startRow, 8).setValue(NEW_ISSUE);
}
}
}

How do I bold one line in a Google Docs Script?

I'm writing a script to parse a Google Sheet and format the cells nicely on a Doc. I'd like the cell data from column 1 to always be bold and the cell data from column 6 to always be Italic. The problem is, after appending a paragraph to the document body, the attribute changes are applied to the entire document. Is there a way to bold/italicize the cell data before appending it to the doc body?
function readRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var doc = DocumentApp.create("Smogon Formatted");
var docBody = doc.getBody();
for (var i = 2; i <= numRows; i++) {
for (var j = 1; j <= numCols; j++){
var cellData = rows.getCell(i, j).getValue()
// Format data based on column
if (j == 1) {
docBody.appendParagraph(cellData).editAsText().setBold(true);
} else if (j == 2 || j == 3) {
var imgFormula = rows.getCell(i, j).getFormula();
var imgUrl = getImageUrl(imgFormula);
docBody.appendParagraph("[img]" + imgUrl + "[/img]");
} else if (j == 6) {
docBody.appendParagraph(cellData).editAsText().setItalic(true);
} else {
docBody.appendParagraph(cellData);
}
}
}
};
EDIT: Try #2, using the setAttributes method
function readRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var doc = DocumentApp.create("Smogon Formatted");
var docBody = doc.getBody();
for (var i = 2; i <= numRows; i++) {
for (var j = 1; j <= numCols; j++){
var cellData = rows.getCell(i, j).getValue()
// Format data based on column
if (j == 1) {
docBody.appendParagraph(cellData).setAttributes(style1);
} else if (j == 2 || j == 3) {
var imgFormula = rows.getCell(i, j).getFormula();
var imgUrl = getImageUrl(imgFormula);
docBody.appendParagraph("[img]" + imgUrl + "[/img]");
} else if (j == 6) {
docBody.appendParagraph(cellData).setAttributes(style2);
} else {
docBody.appendParagraph(cellData);
}
}
}
};
// Style definitions as global variables
var style1= {};
style1[DocumentApp.Attribute.BOLD] = true;
var style2= {};
style2[DocumentApp.Attribute.ITALIC] = true;
If you use style attributes you can assign a style to every paragraph very easily, you can actually do it for any document element...
Here is a basic example code to show how it works :
(doc here)
function exportToDoc(){
var doc = DocumentApp.openById('16i----L53WTDpzuLyhqQQ_E');// or create a new doc (but not while you test it :-)
var body = doc.getBody();
var sheet = SpreadsheetApp.getActiveSheet();
var values = sheet.getDataRange().getValues();
for (var i in values){
var rowData = values[i].join(' + ');
if (i == 1) {
body.appendParagraph(rowData).setAttributes(style2);
} else if (i == 2 ) {
body.appendParagraph(rowData).setAttributes(style1)
}
}
doc.saveAndClose();
}
// Style definitions as global variables
var style1 = {};// style example 1
style1[DocumentApp.Attribute.FONT_SIZE] = 10;
style1[DocumentApp.Attribute.FONT_FAMILY] = DocumentApp.FontFamily.CONSOLAS;
style1[DocumentApp.Attribute.FOREGROUND_COLOR] = "#444400";
var style2 = {};// style example 2
style2[DocumentApp.Attribute.FONT_SIZE] = 16;
style2[DocumentApp.Attribute.FONT_FAMILY] =DocumentApp.FontFamily.ARIAL_NARROW;
style2[DocumentApp.Attribute.FOREGROUND_COLOR] = "#005500";
//
example random data result :

Categories

Resources