Removing 5 seconds from a variable in javascript - javascript

I'm hoping to pull a variable from a text box that would be submitted like "201442" turn it into time 20:14:42 then subtract 5 seconds for the output 20:14:37. So far i have:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>-5</title>
<script>
var incomingtime = "0";
</script>
<script>
function calctime(){
incomingtime = document.getElementById("inputtime").value;
alert (incomingtime);
}
</script>
</head>
<body>
<input type="text" id="inputtime"/><input type="text" id="outputtime"/><br>
<button onclick="calctime()">-5 Dat</button>
</body>
</html>
What would be the best approach? Splitting up the input into three sections and doing the math that way? Or is there a simpler solution? How would i go about throwing first two chars into a variable, third and fourth into a var, then 5th and 6th into a var for calculations?

I guess, you should parse your string and put your time into Date() object, then it will be easier to do any computations on your time value
You can parse it in the following way:
timeObj = new Date(0,0,0,
incomingtime.substring(0, 2),
incomingtime.substring(2, 4),
incomingtime.substring(4, 6));
Then you can carry out your values, using object's 'get' functions.
If you want to change its value, you can just add or substract time (in miliseconds). For example, if you want to substract 5 seconds, you should just:
timeObj -= 5*1000;

Related

Javascript in HTML, struggling to make a for loop work for a button

I'm trying to practice using JavaScript in HTML, and am having some trouble.
The goal for me right now is to have a button that, when pressed, prints out a series of breaks and descending numbers down to 1 like a countdown. Once I've got the function implemented into the page, I'd work in a textbox that the user can use to have their own number that counts down to 1. Pretty simple, but I've hit a wall. I'm trying to do this using a .js library located in the same folder as the HTML file. Here's how my HTML looks:
<!doctype html>
<!-- project10.html -->
<html>
<head>
Hello!
</head>
<body>
<title>Testing Function</title>
<script type="text/javascript" src="test.js"></script>
<p id="demo" onclick="myFunction(5)">Click this text to show a countdown.</p>
</body>
</html>
Not the cleanest, I know. Here's the test.js located in the same folder:
function myFunction(b2){
for (i=b2;i>0;i--){
document.getElementById("demo").innerHTML = i;
document.getElementById("demo").innerHTML = "<br>";
}
}
As I see the question, the task is to provide a function a number, and output it in a descending order.
I've created an ul element which will you can append an li tag too on each iteration of the loop so you can see the numbers count down.
I've also changed the p element to a button, as this is more suitable for the given task, you generally click on buttons, not paragraphs.
<html>
<head>
Hello!
</head>
<body>
<title>Testing Function</title>
<script type="text/javascript" src="test.js"></script>
<button onclick="myFunction(5)">
Click this text to show a countdown.
</button>
<ul id='list'>
</ul>
</body>
</html>
Within the Javascript file, I've used your loop, changing the name of the parameter being passed in, this was done to be as descriptive as possible.
From here, we count down, with each loop decreasing the value of the number you passed in, in your case, 5.
With each loop, we create a new li element, we then add innerHTML to it, the value of that being the current value in the loop, which is then appended to the ul element.
function myFunction(number){
const ul = document.getElementById('list')
for (i = number; i > 0; i--){
let item = document.createElement('li')
item.innerHTML = i
ul.appendChild(item)
}
}

Arithmetic sequence within an array using doc.write to display Javascript

So the objective is to make an arithmetic sequence starting 7 with difference of 9. So 7, 16, 25, 34 etc.
You have to do this 20 times and make a one column table that autogenerates the rows per number using document.write() to print it.
I believe I understand to make an array of 20 and input the math within the array. So this is what I have so far,
<!DOCTYPE html>
<html lang="en">
<head>
<title>Javascript Arithmetic Sequence</title>
<meta charset="UTF-8" />
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
</head>
<body>
<script type ="text/javascript">
var result =[20];
for (var a = 7; a + 9; a++) {
document.write("<table>"+
"<tr>"+
"<th> Arithmetic Sequence of 7</th>"+
"<td>"+ result+"</td>"+
"</tr>"+
"</table>");
}
</script>
<p>Question 1: You would need to change the array length.</p>
<br>
<p>Question 2: You use document.write() to display HTML document content and not pop up as a button/alert using alert().</p>
</body>
</html>
The problem is, nothing shows on my HTML website and the JS validators keep saying document.write() can be used as an "eval" (which I don't understand what that means). I've scanned my chapter up and down, googled some advice (which goes way outside what the chapter is about). Looking to see if anyone can spot where I might be wrong or give advice on what I need to adjust.
Thanks.
Played around with it and finally got the answer. Thanks everyone who helped too!
<script type ="text/javascript">
var table = "<table border =1><tr><th>Arithmetic Sequence of d=9</th></tr>";
var result = 7 ;
for (var count = 0; count <20; count++) {
result = result + 9;
table+="<tr><td>"+ result +"</td>",
"</tr>";
}
table+="</table>";
document.write(table);
</script>

Button code preference

Im new to Javascript and this site. Below are 2 codes (only HTML, normal i work with external js files) which deliver a button what you can click for a date. I was wondering which code has the preference amongst the developers and is there any advantage from 1 another? The way i see it is that adding a function is overkill.
Code 1
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="utf-8">
</head>
<body>
<button onclick="document.getElementById('demo').innerHTML = Date()">The time is?</button>
<p id="demo"></p>
</body>
</html>
Code 2
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="utf-8">
</head>
<body>
<button onclick="myFunction()">The time is?</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = Date();
}
</script>
</body>
</html>
The second one is way better, you are separating the js from the html.
If you have two buttons with the same function, it will be easier to avoid duplicated code and to maintain with the second version!
For example if you want to change the behaviour of your buttons, you won't have to modify your html and be able to change the beviour every where at once.
In my opinion the correct answer here is neither of both.
To write maintainable and readable code, the best practice is to have a complete separation between HTML, CSS and JavaScript. Making the assumption that "it's only one line", is pretty dangerous, as one line quickly becomes two and so on. It's better to always use the same rules instead of making exceptions for one-liners.
Personally, I would write HTML like this:
<button class="time-button"></button>
<p id="demo"></p>
<script src="script.js"></script>
In script.js, you can then attach an event listener like this:
// Note that querySelector might not be supported in really old browsers
var timeButton = document.querySelector('.time-button');
var demoParagraph = document.getElementById('demo');
// Or attachEvent for IE < 11
timeButton.addEventListener('click', timeFunction);
/**
* Here you can write some beautiful comments about the function
*/
function timeFunction (eventData) {
demoParagraph.innerHTML = new Date().toISOString();
}
In case you write it like that you can start listening (addEventListener) and stop listening (removeEventListener) whenever you want to.
It's recommended to put the elements in a variable, since looking up an element is pretty slow.
I'd say :
Both are correct depending on what you want to do with it.
First way : OK if the function is short and not complex, no re-use purpose.
Second way : OK if the function is complex, need to be maintained and plus : you can re-use it and avoid code duplication.
Now another approach is to extract javascript methods in another .js file.

What should I tweak in the Javascript/HTML to make this random quote generator work?

<!DOCTYPE html>
<html>
<head>
<title>Quote Gen</title>
<script src="jquery-3.1.1.min.js"></script>
<script>
var Quotes = ['Thousands of candles can be lighted from a single candle, and the life of the candle will not be shortened. Happiness never decreases by being shared.','Happiness is the art of never holding in your mind the memory of any unpleasant thing that has passed.','To be happy, we must not be too concerned with others.','Change your thoughts and you change your world.','hello'];
function newQuote(){
var RandomNumber = Math.floor(Math.random())*Quotes.length;
$("#QuoteDisplay").text(Quotes[RandomNumber]);
}
</script>
</head>
<h5>
Simple Quote Generator
</h5>
<body>
<p id = "QuoteDisplay">
</p>
<button onclick="newQuote()">New Quote!</button>
</body>
</html>
This is a simple Quote Generator that I am building as a part of FreeCodeCamp. The aim is basically to generate a new Quote whenever the user clicks on the Buttton. However when I click on the button the text isn't getting displayed. What is wrong/missing in my code?
You just need make sure that you have the JQuery library referenced BEFORE the script is encountered AND then to move a single parenthesis in this line:
var RandomNumber = Math.floor(Math.random())*Quotes.length;
So that it is:
var RandomNumber = Math.floor(Math.random()*Quotes.length);
By moving the closing parenthesis so that it comes AFTER Quotes.length, you ensure that the random number that is generated (from 0 to 1) gets multiplied by the length of the array BEFORE getting rounded down. If you don't do this, the random number will always get rounded down to 0.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Quote Gen</title>
<script src="jquery-3.1.1.min.js"></script>
<script>
var Quotes = ['Thousands of candles can be lighted from a single candle, and the life of the candle will not be shortened. Happiness never decreases by being shared.','Happiness is the art of never holding in your mind the memory of any unpleasant thing that has passed.','To be happy, we must not be too concerned with others.','Change your thoughts and you change your world.','hello'];
function newQuote(){
var RandomNumber = Math.floor(Math.random()*Quotes.length);
$("#QuoteDisplay").text(Quotes[RandomNumber]);
}
</script>
</head>
<h5>
Simple Quote Generator
</h5>
<body>
<p id = "QuoteDisplay"></p>
<button onclick="newQuote()">New Quote!</button>
</body>
</html>
Math.floor(Math.random()) always return 0 so anything you multiply it by will be 0
RandomNumber is always 0
Also, is a good practice to declare Javascript variables with the first letter lowercase.
Stick to jQuery if you're using it, avoid onclick on the DOM if you can use jQuery click event.
This is the working example with some fixes.
https://jsbin.com/meqetumini/edit?html,js,output
function newQuote(){
var RandomNumber = Math.floor(Math.random()*Quotes.length);
$("#QuoteDisplay").text(Quotes[RandomNumber]);
}
$('#new-quote-btn').click(newQuote)

Jscript not printing to element

I have no idea why this isn't working. I mean as far as I know It should print my array in alphabetical order to the div "output"
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title> Lexicographic ordering </title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var words = [];
var input = prompt("Please enter a word or type end to stop prompts");
while (input != 'end') {
words.push(input);
input = prompt("Please enter a word or type end to stop prompts");
}
words.sort();
getElementById('#output').innerHTML= words.join();
</script>
</head>
<body>
<header>Lexicographic Ordering </header>
<hr>
<div class ="page-wrapper">
h1> Lexicographic Ordering </h1>
<div id="output"></div>
</div>
</body>
</html>
There are two small bugs in your code, and they're both in this line:
getElementById('#output').innerHTML= words.join();
getElementById is not a part of the window, it's a part of the document object, so you must reference it properly. Also, that method takes an ID, not a selector, so you don't need the # in front of it.
document.getElementById('output').innerHTML= words.join();
That should do what you want! Alternatively, since I notice you have jQuery included, you could do $('#output').innerHTML = ... to achieve the same effects.
You may also try to move the <script> block at the end, just before closing of the </body>. Anywhere after the <div id="output"></div>.
JavaScript on some browsers fails when they have to reference some elements which has not been parsed by their HTML parser when the script is executing or trying to reference them.
Also, you don't use # with getElementById(...);. # is used with Jquery. This is pure JavaScript. Make it getElementById('output').whatever...;
Edit:
Another option suggested by Patrick Evans is to move the JavaScript Code in an onload() event handler method to execute the code. This ensures that the HTML is fully loaded in the DOM before we try to manipulate it.

Categories