I want to show text in div with javascript - javascript

i am trying to make a javascript stopwatch here and i want to add time to div.circle and i don't know whats wrong in this code please help me!! thanks
<-- this is html code --->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>stopwatch</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="box">
<h1>Stopwatch</h1>
<div class="circle"></div>
<div class="buttons">
<button>Start</button>
<button>Stop</button>
<button>Reset</button>
</div>
</div>
</body>
<script>
<-- this is js code -->
let min = 0;
let sec = 0;
let mil = 0;
let time = document.getElementsByClassName("circle");
time = min + " : " + sec + " : " + mil ;
time.innerHTML = time;
console.log (time);
</script>
</html>

let time = document.getElementsByClassName("circle");
time = min + " : " + sec + " : " + mil;
time.innerHTML = time;
Those lines actually set the time variable as an element, but then break it and put it inside a string.
Should be like that:
const time = document.getElementsByClassName("circle");
time.innerHTML = min + " : " + sec + " : " + mil;

Your code has some very fundamental pieces missing. I have changed it a bit to show something on button click but it will require way more efforts than that. I will highly recommend you to go through some tutorial in HTML, CSS, JS for a day or two.
const button = document.getElementsByTagName("button")[0];
button.onclick=() => {
let min = 0;
let sec = 0;
let mil = 0;
let time = document.getElementsByClassName("circle")[0];
let timeString = min + " : " + sec + " : " + mil ;
time.innerHTML = timeString;
console.log(timeString);
}
<div class="box">
<h1>Stopwatch</h1>
<div class="circle"></div>
<div class="buttons">
<button>Start</button>
<button>Stop</button>
<button>Reset</button>
</div>
</div>

Related

JavaScript API fetch does not work on first load

Im working on this currency converting app and ufetching the API from https://exchangeratesapi.io/
The app works except it only fetches the api on refresh. Im using onload in body tag.
Any idea how can I make it work on first load without refreshing?
Thanks in advance
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>JS Bin</title>
<script type="text/javascript" src="indexCurrencyFirst.js" ></script>
<script type="text/javascript" src="indexCurrency.js" ></script>
<link rel="stylesheet" type="text/css" href="styleCurrency.css">
</head>
<body onload="convertCurrencyRight()" >
<nav>
<ul class="navbar">
<li id="logo"><img src="Assets/Logo_openCurren.svg"></li>
<li id="date">Fecha</li>
</ul>
</nav>
<div class="wrapper" >
<div id="containerFrom">
<input id="fromQuantity" type="number" value="1" onchange="convertCurrencyRight()" onkeyup="convertCurrencyRight()"/>
<select id="from" onchange="convertCurrencyRight()" onkeyup="convertCurrencyRight()">
</select>
</div>
<div id="arrow"><img src="Assets/Arrow.svg"> </div>
<div id="containerTo">
<input id="toQuantity" type="number" value="0" onchange="convertCurrencyLeft()" onkeyup="convertCurrencyLeft()"/>
<select id="to" onchange="convertCurrencyRight()" onkeyup="convertCurrencyRight()">
<option value="EUR" selected>EUR</option>
</select>
</div>
</div>
<div class="wrapper" >
<div id="containerCValues">
<p id="currentRateA"> 1 Eur = 0.89 Gbp </p>
<p id="currentRateB"> 1 Gbp = 1.12 Eur </p>
</div>
</div>
</body>
</html>
My JS files
Loaded in head indexCurrencyFirst
//fill the select options with the available currencies
fetch("https://api.exchangeratesapi.io/latest?base=")
.then((resp) => resp.json())
.then(function(data){
var allRates = data.rates;
var selectA = document.getElementById("from");
var selectB = document.getElementById("to");
allRates = Object.entries(allRates)
for(var i = 0; i < allRates.length; i++) {
var opt = allRates[i][0];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
if(opt==="GBP"){
var selectedAtt=document.createAttribute("selected");
el.setAttributeNode(selectedAtt);
}
selectA.appendChild(el);
var la = document.createElement("option");
la.textContent = opt;
la.value = opt;
selectB.appendChild(la);
}
})
.catch(function(error) {
console.log(error);
});
and the functions which convert the rates
function convertCurrencyRight() {
var fromCurrency = document.getElementById("from").value;
var toCurrency = document.getElementById("to").value;
console.log(toCurrency);
fetch("https://api.exchangeratesapi.io/latest?base=" + fromCurrency)
.then((resp) => resp.json())
.then(function(data){
//if both currencies are the same return identical values
(fromCurrency===toCurrency) ?
(document.getElementById("toQuantity").value = document.getElementById("fromQuantity").value,
document.getElementById("currentRateA").textContent= "1 " + fromCurrency + " = " + "...",
document.getElementById("currentRateB").textContent= "")
:
//otherwise return the top value as the multiplication of top currency rate by the amount specied below
(document.getElementById("toQuantity").value = (data.rates[toCurrency]*document.getElementById("fromQuantity").value).toFixed(3),
//change the single amount values
document.getElementById("currentRateA").textContent= "1 " + fromCurrency + " = " + (data.rates[toCurrency]).toFixed(6) + " " + toCurrency,
document.getElementById("currentRateB").textContent= "1 " + toCurrency + " = " + (1/data.rates[toCurrency]).toFixed(6) + " " + fromCurrency)
//load the date of the current rates
var date = document.getElementById("date");
date.innerHTML = "LAST UPDATED " +
data.date.split("-").reverse().join("-");
})
.catch(function(error) {
console.log(error);
});
}
function convertCurrencyLeft() {
...
}
Any idea how to fix this. I tried using jQuery with document ready instead of onload with luck
I'd just get ride of the onload on your body tag and just go with Jquery $(document).ready() and put your call to `convertCurrencyRight() there. In my fiddle this appears to work fine.
$(document).ready(function() {
convertCurrencyRight();
});

Code execution speed is slower and slower in time

In my project I need to see sensors data in textarea window
and after some time to save those data in txt file.
I use this code :
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
var updateInterval = 50;
var updateChart = function(count) {
count = count || 1;
Val1 = Math.floor((Math.random() * 100) + 1);
Val2 = Math.floor((Math.random() * 100) + 1);
Val3 = Math.floor((Math.random() * 100) + 1);
$(document).ready(function() {
var $textarea = $('textarea');
$textarea.scrollTop($textarea[0].scrollHeight);
});
var d = new Date();
$("#output").append(document.createTextNode(d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + " - , " + Val1 + ", " + Val2 + ", " + Val3 + "\n"));
}
setInterval(function() {
updateChart()
}, updateInterval);
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.style.display = 'none';
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);
}
</script>
</head>
<body>
<form onsubmit="download(this['name'].value, this['text'].value)">
Filename: <input type="text" name="name" value=" .txt">
<textarea id='output' cols="40" rows="10" name="text" style="border:solid 2px blue;">
Time ,Val1, Val2, Val3
</textarea>
<input type="submit" value="SAVE">
</form>
</body>
</html>`
The problem is in the fact: my code execution speed is slower and slower if time
between start and file saving moment is longer !
If I use 20 samples/sec this amount of slowdown is not acceptable.
Is it possible to get faster code and much less dependent of time (txt file size) ?

Don't find why my function don't change the temperature degree from Celsius to Fahrenheit

I do a weather app for Free code camp, but i don't know why my button don't change the temperature from celsius to fahrenheit.
I think it's a problem for the recuperation of the variable but i don't know where.
I try some change in my code but i just go around in circles.
This is my javascript :
$(document).ready(function(){
var long;
var lat;
var celsius;
var fahrenheit;
navigator.geolocation.getCurrentPosition(function(position){
long = position.coords.longitude;
lat = position.coords.latitude;
var url = 'http://api.openweathermap.org/data/2.5/weather?lat='+lat+'&lon='+long+'&lang=fr'+'&units=metric&appid=d475e2ed504ab40f4de6c1b3cba9ebcc';
$.getJSON(url, function(data){
var weatherType = data.weather[0].description;
var windSpeed = data.wind.speed;
var icon = data.weather[0].icon;
var city = data.name;
var country = data.sys.country;
var description = data.weather[0].description;
var celsius = data.main.temp;
var fahrenheit = celsius * 9/5 +32;
var Temp = celsius;
$('.card').html( city + '<br> Temp: '+Temp+' °C'+ '<br> Wind Speed:'+windSpeed+'M/s');
$('.icon').html('<img src="http://openweathermap.org/img/w/' + icon + '.png" /> ' + '<br>'+weatherType);
function change() {
if (Temp == 'fahrenheit') {
Temp = 'celsius';
} else if (Temp == 'celsius') {
Temp = 'fahrenheit';
}
$('.btn').on('click', function() { change (); })
console.log(city);
console.log(weatherType);
console.log(windSpeed);
console.log(icon);
};
})
})
});
and the HTML :
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<title>Weather App</title>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class='col-sm-6 col-sm-offset-3 col-xs-6 col-xs-offset-3 weather' >
<div class="col-sm-6 text-center card">
</div>
<div class="col-sm-6 text-center text-uppercase icon">
</div>
<button type="button" class="btn degree">°C/°F</button>
</div>
</div>
</div>
<div class="text-center footer">by Mathieu Dupré-Fontana
</div>
<script src="js/app.js"></script>
Can somebody help me please?
Ps: Sorry for my bad English, i'm French .
celsius appears to be a number, not a string, when Temp is set to the value of celisus, Temp is set to a number, not a string
var celsius = data.main.temp;
var fahrenheit = celsius * 9/5 +32;
var Temp = celsius;
Temp would not be equal to "fahrenheit" or "celcius" within change function
function change() {
if (Temp == 'fahrenheit') {
Temp = 'celsius';
} else if (Temp == 'celsius') {
Temp = 'fahrenheit';
}
}
.html() should also be called within change() function, if the expected result is to toggle Celcius and Fahrenheit rendering at HTML on click at element.

JavaScript string doesn't get displayed on the page

pretty new to javascript and doing some examples from a book, can't understand why this isn't producing any text strings on the page when loaded.
function init()
{
var sum = 80 + 20;
var sub = sum - 50;
var mul = sum * 5;
var div = sum / 4;
var mod = sum % 2;
var inc = ++sum;
var dec = --sum;
var str = "Sum: " + sum;
str += "<br>Subtraction: " + sub;
str += "<br>Multiplication: " + mul;
str += "<br>Division: " + div;
str += "<br>Modulus: " + mod;
str += "<br>Increment: " + inc;
str += "<br>Decrement: " + dec;
document.getElementById( "Panel" ).innerHTML = str;
}
document.addEventListener("DOMContentLoaded" , init , false);
And the html5 code;
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="arithmetic.js"></script>
<title>Doing Arithmetic</title>
</head>
<body>
<div id="panel"> </div>
</body>
</html>
Your <div> has an id of panel, not Panel. The IDs need to match. So you can either change the JavaScript code:
document.getElementById( "panel" )
or the HTML:
<div id="Panel"> </div>
Replace
<div id="panel"> </div>
with
<div id="Panel"> </div>
and it will work. P in panel should be capital.

jQuery code not working on my local machine

Below code works fine on http://jsfiddle.net/saQTw/2/
for some reason it doesnt work on my local machine, i am not sure where i am making the mistake. Need an expert eye to look what i am doing wrong in this code.
Code which i got from the stackoverflow is support to populate the select list with dates
but i cant make it work on my local machine.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<link href="css.css" rel="stylesheet" type="text/css" />
<script>
function pad(n){return n<10 ? '0'+n : n}
var date = new Date();
var selectElement = $('<select>'), optionElement;
for (var count =0; count < 90; count++){
formattedDate = pad(date.getUTCDate()) + '-' + pad(date.getUTCMonth()+1) + '-' + date.getUTCFullYear();
optionElement = $('<option>')
optionElement.attr('value',formattedDate);
optionElement.text(formattedDate);
selectElement.append(optionElement);
date.setDate(date.getDate() + 1);
}
$('#ddDate').append(selectElement);
</script>
</head>
<body>
<div id="ddDate"> </div>
</body>
</html>
I tried jQuery version 1.6 also it does not work
Solution for the above problem:
<script>
$(function(){
function pad(n){return n<10 ? '0'+n : n}
var date = new Date();
var selectElement = $('<select>'), optionElement;
for (var count =0; count < 90; count++){
formattedDate = pad(date.getUTCDate()) + '-' + pad(date.getUTCMonth()+1) + '-' + date.getUTCFullYear();
optionElement = $('<option>')
optionElement.attr('value',formattedDate);
optionElement.text(formattedDate);
selectElement.append(optionElement);
date.setDate(date.getDate() + 1);
}
$('#ddDate').append(selectElement);
});
</script>
try wrapping the jquery in a document.ready()
<script>
jQuery(document).ready(function) {
You are accessing the #ddDate element before it exists. So either move the javascript part beneath the body OR wrap the code into $(document).ready(function() {...})
In JSFiddle you are using the onload event to run pad(n). You need to do the same here
Modify the <body> tag to <body onload="pad(2)">

Categories

Resources