I'm learning HTML, CSS, and Javascript with Coder on the Raspberry pi. Currently, I'm trying to make a simple page that displays time, date, and the current weather. Something is going wrong with the $.getJSON call in the getWeather() function.
Typing the URL passed to $.getJSON works correctly (i.e., a page is loaded with all the information in JSON), but the "Got Weather" string is never displayed. I've also tried using the AJAX call requesting JSON or JSONP data type. Neither of those methods worked either. What am I missing?
$(document).ready( function() {
//This code will run after your page loads
function displayTime() {
var current_time = new Date();
var hours = current_time.getHours();
var minutes = current_time.getMinutes();
var seconds = current_time.getSeconds();
var meridiem = "AM"; // default is AM
var day = current_time.getDay();
if(seconds < 10) {
seconds = "0" + seconds;
}
if(minutes < 10) {
minutes = "0" + minutes;
}
// Set the meridiem for a 12hr clock
if(hours > 12) {
hours -= 12;
meridiem = "PM"
} else {
meridiem = "AM"
}
var clock_div = document.getElementById('clock');
clock_div.innerText = hours + ":" + minutes + ":" + seconds + " " + meridiem;
// Depending on the value of 'day', set the corresponding string
var day_div = document.getElementById('day');
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var today = weekday[current_time.getDay()];
day_div.innerText = today;
// Get the date information
var date = current_time.getDate();
// Get the year
var year = current_time.getFullYear();
// Get the month and set the string
var month = new Array(12);
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var this_month = month[current_time.getMonth()];
// set the string
var date_div = document.getElementById('date');
date_div.innerText = this_month + " " + date + " " + year;
}
function getWeather() {
var api_key = REMOVED; // API key for open weather
var weather_api = "http://api.openweathermap.org/data/2.5/weather?lat=40.115&lon=-88.27&units=imperial&appid=" + api_key;
var weather_div = document.getElementById('weather');
$.getJSON(weather_api).then(function(result){
//alert("City: "+result.city.name);
//alert("Weather: "+ result.list[0].weather[0].description);
weather_div.innerText = "Got Weather";
});
//weather_div.innerText = "Got Weather";
}
// This runs the displayTime function the first time
displayTime();
getWeather();
// This makes the clock "tick" repeatedly by calling it every 1000 ms
setInterval(displayTime, 1000);
setInterval(getWeather, 2000);
});
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Coder</title>
<meta charset="utf-8">
<!-- Standard Coder Includes -->
<script>
var appname = "{{app_name}}"; //app name (id) of this app
var appurl = "{{&app_url}}";
var staticurl = "{{&static_url}}"; //base path to your static files /static/apps/yourapp
</script>
<link href="/static/apps/coderlib/css/index.css" media="screen" rel="stylesheet" type="text/css"/>
<script src="/static/common/js/jquery.min.js"></script>
<script src="/static/common/ace-min/ace.js" type="text/javascript" charset="utf-8"></script>
<script src="/static/apps/coderlib/js/index.js"></script>
<script>
Coder.addBasicNav();
</script>
<!-- extra inludes to get weather from OpenWeather -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.0.min.js"><\/script>')</script>
<script src="js/vendor/jquery-ui.min.js"></script>
<!-- End Coder Includes -->
<!-- This app's includes -->
<link href="{{&static_url}}/css/index.css" media="screen" rel="stylesheet" type="text/css"/>
<script src="{{&static_url}}/js/index.js"></script>
<!-- End apps includes -->
</head>
<body>
<div id='day'></div><br>
<div id='date'></div>
<div id='clock'></div>
<div id='weather'></div>
</body>
</html>
CSS:
body {
background-color: black;
}
#day {
height:100px;
width: 300px;
margin-left: 10px;
padding-top: 50px;
position: fixed;
top: 0px; left: 20px;
font-family: courier, monospace;
text-align: center;
color: white;
font-size: 30px;
font-weight: bold;
}
#date {
height:100px;
width: 300px;
margin-left: 10px;
padding-top: 50px;
position: fixed;
top: 50px; left: 20px;
font-family: courier, monospace;
text-align: center;
color: white;
font-size: 20px;
}
#clock {
height:100px;
width: 300px;
margin-left: 10px;
padding-top: 50px;
position: fixed;
top: 100px; left: 20px;
font-family: courier, monospace;
text-align: center;
color: white;
font-size: 20px;
}
I found the issue. Opening up the developer console showed an error along the lines of "Blocked loading mixed active content...". It seems I need to better familiarize myself with the developer tools.
Apps built within Coder are accessed over HTTPS. However, the call to openweather is over HTTP. The openweather API permits HTTPS calls only if you have a pro (paid) subscription. Fortunately, https://forecast.io allows a set number of free calls per day and uses HTTPS.
Related
so I'm currently making a clicker game With a twist that the only thing that makes you bottles are bottlers, but they are directly upgraded along with the bottle type throughout the game until you can beat it, and here is my code so far. if you run the code you can see that pressing the upgrade button more than once only returns an error, how do I fix this? also if anyone has any tips to improve or shorten the code I'll take that as well as this is my first time coding.
<html>
<head>
<link rel="icon" href="bottle1.png">
<title>Bottle empire</title>
<style>
p.cash {
font-family: "Comic Sans MS", "Comic Sans", cursive;
position: relative;
left: -5px;
}
p.cookie {
font-family: "Comic Sans MS", "Comic Sans", cursive;
position: relative;
top: -300px;
}
</style>
</head>
<center>
<p class="cash">Cash: <span id="score">0</span></p>
</center>
<center><img src="bottle1.png" height="256px" width="256px" onclick="addToScore(1)"></center>
<Center><button onclick="upgrade()">Upgrade bottle [<span id="upgradecost">1000</span>] </button></Center>
<button onclick="buybottler()">Bottler [<span id="bottlercost">10</span>] -- <span id="bottlers">0</span></button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/3.0.0/js.cookie.min.js"></script>
<script>
var score = 1000000;
var bottlercost = 10;
var bottlers = 0;
var upgradecost = 1000;
function buybottler() {
if (score >= bottlercost) {
score = score - bottlercost;
bottlers = bottlers + 1;
bottlercost = Math.round(bottlercost * 1.15);
document.getElementById("score").innerHTML = score;
document.getElementById("bottlercost").innerHTML = bottlercost;
document.getElementById("bottlers").innerHTML = bottlers;
document.getElementById("upgradecost").innerHTML = upgradecost
}
}
function upgrade() {
if (score >= upgradecost) {
score = score - upgradecost;
upgrade = upgrade + 1;
upgradecost = upgradecost * 5;
document.getElementById("score").innerHTML = score;
document.getElementById("upgradecost").innerHTML = upgradecost
}
}
function addToScore(amount) {
score = score + amount
document.getElementById("score").innerHTML = score;
}
setInterval(function () {
score = score + bottlers
document.getElementById("score").innerHTML = score;
}, 2000); // 2000 msec = 1 sec
</script>
</body>
</html>
You're reassigning the value of upgrade in the upgrade function itself (therefore essentially removing your upgrade() function)
function upgrade() {
if (score >= upgradecost) {
score = score - upgradecost;
upgrade = upgrade + 1; // Here
...
I'm not sure what you're trying to achieve with this line, but removing it will fix your error problem
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'; ?>;
I have made this script below to change a value of one cell and the PDF that page into a document. It works well but only the first 5 or 6 PDFs are creating properly and the rest seem to be 'luck of the draw'. Some are fine and others give me a HTML error message.
Here is my code:
function CreateClassPacks() {
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
var foldersave=DriveApp.getFolderById('xxxxxxxxxxxxxxxxxxxxx');
var d= new Date();
var dateStamp = d.getDate()+"/"+d.getMonth()+"/"+d.getYear();
var request = {
"method": "GET",
"headers":{"Authorization": "Bearer "+ScriptApp.getOAuthToken()},
"muteHttpExceptions": true
};
var key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
var fetch='https://docs.google.com/spreadsheets/d/'+key+'/export?format=pdf&size=A4&portrait=false'
var classCodeSheetNum = 0
var dataRange = SpreadsheetApp.getActiveSpreadsheet().getSheets()[classCodeSheetNum].getRange(2, 1, 10, 1);
var data = dataRange.getValues();
Logger.log(data)
var sheetNum = 1
for (var r=0; r<(data.length)-1; r++) {
for (i in data[0]) {
SpreadsheetApp.getActiveSpreadsheet().getSheets()[sheetNum].getRange('A2').setValue(data[r][i]);
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getSheets()[sheetNum];
var classCode = sheet.getRange("A2").getValue();
for(var w=0; w< sheetNum;w++)
{
sheet = source.getSheets()[w];
sheet.hideSheet();
}
var name = classCode + " " + dateStamp + ".pdf";
var pdf = UrlFetchApp.fetch(fetch, request);
pdf = pdf.getBlob().setName(name);
var file = foldersave.createFile(pdf)
for(var q=0; q< sheetNum;q++)
{
sheet = source.getSheets()[q];
sheet.showSheet();
}
}
}
}
This is what i get in place of the files that are not correctly created as PDFs:
<!DOCTYPE html><html lang="en"><head><meta name="description" content="Web word processing, presentations and spreadsheets"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0"><link rel="shortcut icon" href="//ssl.gstatic.com/docs/common/drive_favicon1.ico"><title>Too Many Requests</title><link href="//fonts.googleapis.com/css?family=Product+Sans" rel="stylesheet" type="text/css"><style>/* Copyright 2017 Google Inc. All Rights Reserved. */
.goog-inline-block{position:relative;display:-moz-inline-box;display:inline-block}* html .goog-inline-block{display:inline}*:first-child+html .goog-inline-block{display:inline}#drive-logo{margin:18px 0;position:absolute;white-space:nowrap}.docs-drivelogo-img{background-image:url('//ssl.gstatic.com/images/branding/googlelogo/1x/googlelogo_color_116x41dp.png');background-size:116px 41px;display:inline-block;height:41px;vertical-align:bottom;width:116px}.docs-drivelogo-text{color:#000;display:inline-block;opacity:0.54;text-decoration:none;font-family:'Product Sans',Arial,Helvetica,sans-serif;font-size:32px;text-rendering:optimizeLegibility;position:relative;top:-6px;left:-7px;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}#media (-webkit-min-device-pixel-ratio:1.5),(min-resolution:144dpi){.docs-drivelogo-img{background-image:url('//ssl.gstatic.com/images/branding/googlelogo/2x/googlelogo_color_116x41dp.png')}}</style><style type="text/css">body {background-color: #fff; font-family: Arial,sans-serif; font-size: 13px; margin: 0; padding: 0;}a, a:link, a:visited {color: #112ABB;}</style><style type="text/css">.errorMessage {font-size: 12pt; font-weight: bold; line-height: 150%;}</style></head><body><div id="outerContainer"><div id="innerContainer"><div style="position: absolute; top: -80px;"><div id="drive-logo"><span class="docs-drivelogo-img" title="Google logo"></span><span class="docs-drivelogo-text"> Drive</span></div></div>Wow, this file is really popular! It might be unavailable until the crowd clears. Try again.</div></div></body><style>#outerContainer {margin: auto; max-width: 750px;}#innerContainer {margin-bottom: 20px; margin-left: 40px; margin-right: 40px; margin-top: 80px; position: relative;}</style></html>
I would love it if anyone could help as this is killing me lol!
As the error says, it is because you are sending too many requests.
Try having a sleep of about 30ms or so in between your calls:
Utilities.sleep(30);
var file = foldersave.createFile(pdf);
This can slow down the requests and might work.
I'm working on a game named Factory Tycoon and have spotted a bug which I can't resolve myself. Every second you get plus what your items per second is on your items but it is failing to do so. Feel free to test the code. Code:
<!DOCTYPE html>
<html>
<head>
<title>Factory Tycoon</title>
<script type="text/javascript">
var money = 1000;
var items = 0;
var itemsps = 1;
var dropper1Cost = 100;
var dropper1Audio = new Audio('Audio/dropper1Sound.mp3');
function addDropper() {
if (money <= dropper1Cost - 1) {
alert('Not Enough Money.')
}
if (money >= dropper1Cost) {
dropper1Audio.play()
itemsps += 1;
money -= dropper1Cost;
dropper1Cost += 100;
}
}
setInterval(function renderMoney() {
document.getElementById('money').innerHTML = "Money:" + money;
})
setInterval(function renderItemsProcessedPS() {
document.getElementById('items').innerHTML = "Items Processed:" + items;
})
setInterval(function renderItemsProcessedPS() {
document.getElementById('itemsps').innerHTML = "Items Processed Per Second:" + itemsps;
}, 1000)
</script>
</head>
<h4 id="money"></h4>
<h4 id="items"></h4>
<h4 id="itemsps"></h4>
<body>
<img src="Images/dropper1IMG.png" onclick="addDropper()">
</html>
There isn't much code as I've only just started to develop it tonight :).
There is a few issues in the code:
<h4> elements need to be inside the <body> element
the </body> end tag is missing
the setInterval is called before all elements had a chance to load, which will make it error, so I wrapped them in an init function and called that on body load
Side note, this code can be optimized with addEventListener for the load event etc., but here you have a start
<!DOCTYPE html>
<html>
<head>
<title>Factory Tycoon</title>
<style>
span { display: inline-block; padding: 5px; background: #ddd; }
</style>
<script type="text/javascript">
var money = 1000;
var items = 0;
var itemsps = 1;
var dropper1Cost = 100;
var dropper1Audio = new Audio('Audio/dropper1Sound.mp3');
function addDropper() {
if (money <= dropper1Cost - 1) {
alert('Not Enough Money.')
}
if (money >= dropper1Cost) {
dropper1Audio.play()
itemsps += 1;
money -= dropper1Cost;
dropper1Cost += 100;
}
}
function init() {
setInterval(function renderMoney() {
document.getElementById('money').innerHTML = "Money:" + money;
})
setInterval(function renderItemsProcessedPS() {
document.getElementById('items').innerHTML = "Items Processed:" + items;
})
setInterval(function renderItemsProcessedPS() {
document.getElementById('itemsps').innerHTML = "Items Processed Per Second:" + itemsps;
}, 1000)
}
</script>
</head>
<body onload="init();">
<h4 id="money"></h4>
<h4 id="items"></h4>
<h4 id="itemsps"></h4>
<span onclick="addDropper()">Click Me</span>
</body>
</html>
I'm helping my I.T teacher to create easter eggs for some tasks, and I would like to create a countdown timer with html.
Explanation:
Everytime you enter into a website, the countdown timer starts.
Example:
I have a html code with a countdown timer at 30 min, if I go into the website, the countdown timer starts going down, but if I refresh the website, it reset.
I hope you will understand, thanks!
If you want to use only javascript, without any server-side language you could store the time that is left in the localStorage variable, because after you exit the website/browser it will stay the same;
Example:
function countdown() {
time = parseInt(localStorage.time); //All variables in localstorage are strings
//Resets timer if cannot parse the localStorage.time variable or if the time is greater than 30 mins
if(isNaN(time) || time > (30*60)) {
alert("An error occured: time left variable is corrupted, resetting timer");
localStorage.time = 30*60; //30 mins in seconds
countdown();
return null;
}
//Decrementing time and recalling the function in 1 second
time--;
localStorage.time = time;
setTimeout('countdown()', 1000);
}
You can add a function that turn seconds into: Minutes:Seconds and edit the function so it will change an element everytime it calls it self, or do something when the time reaches 0(don't forget to call it once, unless the timer won't run). Good luck!
I made a pen for you:
http://codepen.io/DaCurse0/pen/kkxVYP
It should have everything you need.
P.S: you should probably remove the alert when checking if timer is corrupted because it will show when the timer wasn't set.
html code:
<h1>Countdown Clock</h1>
<div id="clockdiv">
<div>
<span class="days"></span>
<div class="text">Days</div>
</div>
<div>
<span class="hours"></span>
<div class="text">Hours</div>
</div>
<div>
<span class="minutes"></span>
<div class="text">Minutes</div>
</div>
<div>
<span class="seconds"></span>
<div class="text">Seconds</div>
</div>
</div>
css code:
#clockdiv{
font-family: sans-serif;
color: #fff;
display: inline-block;
font-weight: 100;
text-align: center;
font-size: 30px;
}
#clockdiv > div{
padding: 10px;
border-radius: 3px;
background: #00BF96;
display: inline-block;
}
#clockdiv div > span{
padding: 15px;
border-radius: 3px;
background: #00816A;
display: inline-block;
}
.text{
padding-top: 5px;
font-size: 16px;
}
javascript code:
function getTimeRemaining(endtime) {
var t = Date.parse("June 31,2017") - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime) {
var clock = document.getElementById(id);
var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
var deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
initializeClock('clockdiv', deadline);
in the html documnet,include the new files:
<script type="text/javascript" src="assets/js/count.js"></script>
<link rel="stylesheet" type="text/css" href="assets/css/flipclock.css">
hope it works...