How to write to page in javascript using date method - javascript

I want to display a quote depending on what day it is. Example: Quote of the day is Tuesday March 10 : "Quote here". I have the alert displaying the date, day and time but I want it to display on the page in the h2 header. So after it loads the alert I want the quote, depending on which day it is, to be written on the page.
Thank you.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Class 6 array assignment starter file</title>
<script>
var venomArray = new Array();
venomArray[0] = " Ability is nothing without opportunity - Napoleon Bonaparte";
venomArray[1] = " Nothing happens unless first we dream - Carl Sandburg";
venomArray[2] = "quote3";
var today = new Date();
//var text = document.getElementById('expression').firstChild.nodeValue = venomArray[i];
// if I uncomment this, It displays the index 1 for tuesday. How do I get it to write to the page? Would I use firstChildnodeValue?
alert("The quote of the day for: "+today+ venomArray[today.getDay()-1]);
</script>
</head>
<body>
<section>
<h2 style = "color:red" id='expression'> Quote of the Day : </h2>
<h3> All of the Quotes are listed below:</h3>
<p>
Nothing happens unless first we dream - Carl Sandburg<br>
Believe you can and you're halfway there - Theodore Roosevelt<br>
A place for everything, everything in its place - Benjamin Franklin<br>
Don't let the fear of striking out hold you back - Babe Ruth<br>
We can't help everyone, but everyone can help someone - Ronald Reagan<br>
With self-discipline most anything is possible - Theodore Roosevelt
</p>
</section>
</body>
</html>

You need to set the innerHTML property of the element
document.getElementById("expression").innerHTML = ' Quote of the Day : ' +
today+venomArray[today.getDay()-1];

Check this.. This may help your question
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Class 6 array assignment starter file</title>
</head>
<body>
<section>
<h2 style = "color:red" id='expression'> Quote of the Day : <span id="quote"></span> </h2>
<h3> All of the Quotes are listed below:</h3>
<p>
Nothing happens unless first we dream - Carl Sandburg<br>
Believe you can and you're halfway there - Theodore Roosevelt<br>
A place for everything, everything in its place - Benjamin Franklin<br>
Don't let the fear of striking out hold you back - Babe Ruth<br>
We can't help everyone, but everyone can help someone - Ronald Reagan<br>
With self-discipline most anything is possible - Theodore Roosevelt
</p>
</section>
<script type="text/javascript">
var venomArray = new Array();
venomArray[0] = " Ability is nothing without opportunity - Napoleon Bonaparte";
venomArray[1] = " Nothing happens unless first we dream - Carl Sandburg";
venomArray[2] = "quote2";
venomArray[3] = "quote3";
venomArray[4] = "quote4";
var t = new Date();
//alert(t.getDay());
//var text = document.getElementById('expression').firstChild.nodeValue = venomArray[i];
// if I uncomment this, It displays the index 1 for tuesday. How do I get it to write to the page? Would I use firstChildnodeValue?
// alert("The quote of the day for: "+today+ venomArray[today.getDay()-1]);
document.getElementById("quote").innerHTML = venomArray[t.getDay()-1];
</script>
</body>
</html>

You can use innerHtml property of an element to update the content, something like:
document.getElementById('expression').innerHTML = "Quote";
This is an implementation in pure JavaScript. You usually use some kind of templating now a days to display variable text in a web page.

Use This :-
<script>
var venomArray = new Array();
venomArray[0] = " Ability is nothing without opportunity - Napoleon Bonaparte";
venomArray[1] = " Nothing happens unless first we dream - Carl Sandburg";
venomArray[2] = "quote3";
var today = new Date();
//var text = document.getElementById('expression').firstChild.nodeValue = venomArray[i];
// if I uncomment this, It displays the index 1 for tuesday. How do I get it to write to the page? Would I use firstChildnodeValue?
//alert("The quote of the day for: "+today+ venomArray[today.getDay()-1]);
/*Add this Code*/
var display_date = "today"+ venomArray[today.getDay()-1];
$('h2').html(display_date );
</script>

Related

JS HTML Time value.getHours() is showing NaN

I am learning JS and as part of this I was trying to build a HTML page where based on date and time input of EST, I will get IST date and hour in the label. However, I am struggling to get hours and minutes out from HTML input so that I can set these hours into selected. If any of you experts can help me out here, will be really appreciated.
<HTML>
<HEAD>
<script language="JavaScript">
function calcTime() {
var output = document.getElementById("result");
var selectedDate = document.getElementById('date').value;
var selectedTime = document.getElementById('time');
selectedDate.setHours(selectedTime.getHours());
selectedDate.setMinutes(selectedTime.getMinutes());
var traceHours = new Time(selectedTime);
var markHours = traceHours.getHours();
nd = new Date(selectedTime + (3600000 * 9.5));
output.innerHTML = updatedDate;
}
</script>
</HEAD>
<BODY>
Select a date:
<input id=date type="date">
<input id=time type="time">
</br>
<button id=submit onclick="calcTime();return false;">Click to check Time</button>
Time to EST is:
<B>
<blink>
<DIV style="background-color: rgb(25, 236, 208)" id=result></DIV>
</blink>
</B>
</BODY>
</HTML>
You have to get the .value of the input elements, which are text, create a new Date from their values and then you can call a Date method on that.
You also have several other HTML and JavaScript problems, for example, there is no such thing as a Time object in JavaScript, so this will fail:
var traceHours = new Time(selectedTime);
Frankly, it's clear that you've gotten this code straight out of 1995 (seriously). There are a lot of things that are no longer correct (i.e. blink has been deprecated for many years [thank God!]).
See the HTML and JavaScript comments below for details.
<HTML>
<HEAD>
<style>
/* Don't do styling in HTML, separate it into CSS */
#result { font-weight:bold; background-color: rgb(25, 236, 208); }
</style>
</HEAD>
<BODY>
Select a date:
<input id=date type="date">
<input id=time type="time"><br> <!-- There's no such thing as </br> -->
<button id="submit">Click to check Time</button>
<!-- Don't use inline event attributes like onClick. Do that work in JavaScript.
Also, don't use an HTML tag because of the formatting the browser applies to
it, like <b>. Styling is done with CSS, not HTML. -->
Time to EST is: <DIV id="result"></DIV>
<!-- Place your <script> element just before the closing BODY tag
so that by the time the parser gets here, all the HTML will have
been read into memory. Also, type=javascript isn't necessary since
that is the default type. -->
<script>
// Get your DOM references just once, not every time the function runs
var output = document.getElementById("result");
var dateElement = document.getElementById('date')
var timeElement = document.getElementById('time');
// Set up events in JavaScript, not with inline HTML event attributes
document.getElementById("submit").addEventListener("click", calcTime);
function calcTime() {
// Create a new Date object from the two HTML inputs
var est = new Date(dateElement.value + " " + timeElement.value);
// Write out the results. Don't use .innerHTML when there is no HTML.
// Use .textContent instead and just call .toISOString() to get UTC time.
result.textContent = 'USA time: '+ est.toISOString();
}
</script>
</BODY>
</HTML>
There's a couple things going on here:
You need to call value after document.getElementById('time'), otherwise you're working with the element
Both selectedDate and selectedTime are just string values, so you won't be able to call DateTime methods like getHours on either of them
To address the above, simply create a new instance of Date using selectedDate and selectedTime like this: var date = new Date(selectedDate + ': ' + selectedTime); This works because the Date constructor can accept any parseable date string (cf, this should be ok for your purposes, but be aware that this won't work on all browsers, so be careful)
You can now display the stringified date on your page
Full code example:
var output = document.getElementById('result');
var selectedDate = document.getElementById('date').value;
var selectedTime = document.getElementById('time').value;
var date = new Date(selectedDate + ': ' + selectedTime);
output.innerHTML = date;
A couple extra things, you'll probably want to add quotes around your id= tags in the HTML; the </br> should be <br /> or just <b>; probably want to stick with lowercase for all your HTML tags; the <blink> tag is considered obsolete and has been deprecated, so you shouldn't use it; setting innerHTML on an element will completely replace the child nodes, so your string "Time to EST is:" will be entirely replaced by the string value for your date object.
Hope this all helps.
Look at answer from #jcjcjcjc.
Furthermore if you really want to access hours and minutes or set the time you can do
var selectedTime = document.getElementById('time').value;
hours = selectedTime.split(":")[0];
minutes = selectedTime.split(":")[1];
document.getElementById('time').value = "13:45:00.000";
you can use getHours() on object Date only
function calcTime() {
var date = document.getElementById("date").value,
time = document.getElementById("time").value;
var dateTime = date +" " + time;
nd = new Date(dateTime);
}
This is a great community, I really appreciate all of you taking time to resolve my problem. Scott Marcus, jcjcjc, 45ccccw32, Leung King Tim and everyone. I was able to resolve my issue by the code provided by Scott. Please find below the final code for anyone looking for this in future.
var output = document.getElementById("result");
var dateElement = document.getElementById('date')
var timeElement = document.getElementById('time');
document.getElementById("submit").addEventListener("click", calcTime);
function calcTime() {
// Create a new Date object from the two HTML inputs
var est = new Date(dateElement.value + " " + (timeElement.value));
if(est.getMinutes>=30){
est.setMinutes(est.getMinutes() + 30);
est.setHours(est.getHours + 1);
}
else{
est.setMinutes(est.getMinutes() + 30);
}
if(est.getHours>=24){
est.setHours(est.getHours() + 9);
est.setDate(est.getDate() + 1);
}
else{
est.setHours(est.getHours() + 9);
}
result.textContent = 'India time: '+ est.toLocaleString();
}
#result { font-weight:bold; background-color: rgb(25, 236, 208); }
<HTML>
<HEAD>
</HEAD>
<BODY>
Select a date:
<input id=date type="date">
<input id=time type="time"><br>
<button id="submit">Click to check Time</button>
Time to EST is: <DIV id="result"></DIV>
</BODY>
</HTML>

Javascript getElementsByTagName - include embedded elements

I am using a fragment of javascript from the internet to collect all the <small></small> elements within a div id 'footnotes' and append them as an ordered list at the end of my document, with links and back links (i.e Easy HTML Footnotes), Footnotes.js:
var DOMsupport = document.getElementsByTagName && document.createElement;
window.onload = function() {
if (!DOMsupport) return;
var footNoteHolder = document.getElementById('footnotes');
var allNotes = footNoteHolder.getElementsByTagName('small');
var notesList = document.createElement('ol');
notesList.className = 'notesList';
for (var i = 0; i < allNotes.length; i++) {
var newA = document.createElement('a');
newA.id = 'text-' + (i + 1);
newA.setAttribute('href', '#footnote-' + (i + 1));
newA.setAttribute('title', 'Jump to footnote');
newA.appendChild(document.createTextNode((i + 1)));
newBackLink = document.createElement('a');
newBackLink.id = 'footnote-' + (i + 1);
newBackLink.setAttribute('href', '#text-' + (i + 1));
newBackLink.setAttribute('title', 'Back to text');
newBackLink.appendChild(document.createTextNode('[back]'));
newNote = document.createElement('li');
newNote.appendChild(document.createTextNode(allNotes[i].firstChild.nodeValue + ' '));
newNote.appendChild(newBackLink);
notesList.appendChild(newNote);
allNotes[i].replaceChild(newA, allNotes[i].firstChild);
}
footNoteHolder.appendChild(document.createElement('hr'));
footNoteHolder.appendChild(notesList);
}
I like the simplicity, no Jquery in sight, but I would like to be able to include line breaks <br> and/or links Click for PubMed inside some of the footnotes.
When I try to include any other elements within the <small></small> tags the text is placed within the body - not collected and placed at the end. e.g.
<!DOCTYPE HTML>
<html>
<head>
<title>MDT Home</title>
</style>
<script type='text/javascript'
src='..\..\js\footnotes.js'>
</script>
</head>
<body>
<span id='footnotes' ><br>
<h2>Welcome to the MDT site<br></h2><br>
I have designed the site in a minimalist style using <a href='https://www.lua.org/' title='Lua'>Lua</a> it should run on all trust machines.<br>
<br>
To use the menu click the icon at the top left. If you have a modern browser you can use keyboard shortcuts [<small>
Alt-M: Menu.<br>
Alt-H: MDT Home.<br>
Alt-K: Hip and Knee.<br>
Alt-A: Foot and Ankle.<br>
Alt-W: Wrist and Hand.<br>
Alt-S: Shoulder and Elbow.<br>
Alt-I: Spine.<br>
Alt-C: Children.<br>
</small>] e.g move to menu by entering Alt-M.
Please read the terms of use before proceeding to review patient data. <br>
<br></span>
</body>
</html>
I'm not sure if the problem lies with the selection of allNotes using getElementsByTagName('small') producing a NodeList object, or is the problem the building of the newNote using allNotes[i].firstChild.nodeValue + ' ' .
Sorry I don't have the original source of this fragment any longer - normally I would credit the author - and ask them directly. In an ideal world I would learn javascript properly instead of culling fragments and pasting then into my pages.
Any help gratefully received.
Gavin
Spurred on by the criticism I have examined each line of this code to find why I can't have elements in my footnotes.
It appears you can't have elements within TextNodes. A post which Mr Thomas is well aware of, having contributed in the comments.
I will not be learning Javascript to find an alternative mechanism of collating fragments which may or may not contain elements. I know there are good bits of Javascript, but DOM coding does not seem to be one of them.

Swapping <p> with Javascript

I'm trying to swap two HTML paragraphs with a JavaScript button. The code seems to all check out, so I can't seem to figure out why it's not working!
HTML:
<p id="p1"> Donald Drumpf paced and loomed behind Hillary Clinton at times during Sunday night's second presidential debate -- a decision possibly driven by stress during the intensely bitter event, according to body language expert Janine Driver. </p>
<p id="p2"> "He's decreasing stress by doing all that movement," Driver said of Drumpf's behavior on CNN's "New Day" on Monday. </p>
<button onclick="swapT()"> Swap </button>
JS:
function swapT()
{
var obj1 = document.getElementById('p1');
var obj2 = document.getElementById('p2');
var temp = obj1.innerHTML;
obj1.innerHTML = obj2.innerHTML;
obj2.innerHTML = temp;
}
I get the error:
Uncaught ReferenceError: swapT is not defined
What's going wrong?
From the error message you got, it seems that your swapT() function is bound to an inline handler before it's defined. If you're going to call the function from an inline handler, first define the function within the <head> of your document:
<html>
<head>
<script>
function swapT() {
var obj1 = document.getElementById('p1');
var obj2 = document.getElementById('p2');
var temp = obj1.innerHTML;
obj1.innerHTML = obj2.innerHTML;
obj2.innerHTML = temp;
}
</script>
</head>
<body>
<p id="p1">Donald Drumpf paced and loomed behind Hillary Clinton at times during Sunday night's second presidential debate -- a decision possibly driven by stress during the intensely bitter event, according to body language expert Janine Driver.</p>
<p id="p2">"He's decreasing stress by doing all that movement," Driver said of Drumpf's behavior on CNN's "New Day" on Monday.</p>
<button onclick="swapT()">Swap</button>
</body>
</html>
My suggestion is to bind the listener when you define your function, instead:
<html>
<body>
<p id="p1">Donald Drumpf paced and loomed behind Hillary Clinton at times during Sunday night's second presidential debate -- a decision possibly driven by stress during the intensely bitter event, according to body language expert Janine Driver.</p>
<p id="p2">"He's decreasing stress by doing all that movement," Driver said of Drumpf's behavior on CNN's "New Day" on Monday.</p>
<button id="swap">Swap</button>
<script>
function swapT() {
var obj1 = document.getElementById('p1');
var obj2 = document.getElementById('p2');
var temp = obj1.innerHTML;
obj1.innerHTML = obj2.innerHTML;
obj2.innerHTML = temp;
}
document.getElementById('swap').addEventListener('click', swapT);
</script>
</body>
</html>
Here are some relevant links for further reference:
Why put JavaScript in the footer of a page?
Where to place Javascript in a HTML file?
Should I write script in the body or the head of the html?
Does javascript have to be in the head tags?

JavaScript embed video that will change everyday

I'm really new to JavaScript so that I don't know how would I embed a video that will change every day. Example video 1 is for Monday and video 2 is for Tuesday something like that. I'd created something similar to this situation but for images only. Don't know how would I make it in video. Can anyone help me please?
This is my sample approach in which images are changing depending on what date was set on your PC and its working really well.
<!DOCTYPE html>
<html>
<title></title>
<head>
<script type="text/javascript">
window.onload = function(){chgDailyVideo();}
function chgDailyVideo()
{
var vid_array = new Array();
vid_array[0] = "sundaypic.jpg"
vid_array[1] = "mondaypic.jpg"
vid_array[2] = "tuesdaypic.jpg"
vid_array[3] = "wednesdaypic.jpg"
vid_array[4] = "thursdaypic.jpg"
vid_array[5] = "fridaypic.jpg"
vid_array[6] = "saturdaypic.jpg"
var txt_array = new Array();
txt_array[0] = "Hi Im Sunday"
txt_array[1] = "Hi Im Monday"
txt_array[2] = "Hi Im Tuesday"
txt_array[3] = "Hi Im Wednesday"
txt_array[4] = "Hi Im Thursday"
txt_array[5] = "Hi Im Friday"
txt_array[6] = "Hi Im Saturday"
var d = new Date();
var i = d.getDay();
document.getElementById("dailyVid").src = vid_array[i];
document.getElementById("dailyTxt").innerHTML = txt_array[i];
}
</script>
<style type="text/css"></style>
</head>
<body>
<p id = "dailyTxt">Hi I'm Sunday</p>
<img src = "sundaypic.jpg" alt"daily vid" title = "daily pic" id="dailyVid"/>
</body>
</html>
Just use <video> tag instead of <img> and let the last two lines remain the same:
document.getElementById("dailyVid").src = vid_array[i];
document.getElementById("dailyTxt").innerHTML = txt_array[i];
// the above line will show up in case <video> isn't supported.
Note that you can only use videos ending with extensions ogg, mp4, etc and the above is the simplest form of how you could embed a video. See the link to know more about it.
Learn more

javascript runtime error 0x800a1391

I'm learning a bit HMTL5 to prepare to the 70-480 exam. I'm trying to do some javascript code. It looks something like this:
function inchestometers(inches) {
if (inches < 0)
return -1;
else {
var meters = inches / 39.37;
return meters;
}
}
var inches = 12;
var meters = inchestometers(inches);
document.write("the value in meters is " + meters);
var hello = document.getElementById("hello");
hello.firstChild.nodeValue = "Hello World";
and I have such html code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Htnl 5 test</title>
<script src="script/test.js"></script>
</head>
<body>
<p id="hello">Hello</p>
</body>
</html>
In my VS 2012 i have used the Asp.net Empty Web application project and added the Js file and also the html file. The problem is that The function runs properly without any exeptions. This function is taken from here: http://msdn.microsoft.com/en-us/library/cte3c772(v=vs.94).aspx
But whem I'm trying to run the code where I'm getting the document element it' crashint with the error like in the subject. What I've investigated is that the hello gets the null value. I've also tried the code thaken from here:
http://msdn.microsoft.com/en-us/library/yfc4b32c(v=vs.94).aspx - the example with the div. I have the same effect.
What is wrong? I know that there were simmilar subjects but I can't seem to find one matching to mine. Thank you kindly for your help.
Regards
Rafal
you are getting a problem because your javascript code is running before the element
<p id="hello">
is defined.
the simplest solution is to include your script at the end of the body section instead of in the head section but this would cause the document.write call to occur after the rest of the content.
another solution would be to place the code inside two functions like this
function do_conversion() {
var inches = 12;
var meters = inchestometers(inches);
document.write("the value in meters is " + meters);
}
function say_hello() {
var hello = document.getElementById("hello");
hello.firstChild.nodeValue = "Hello World";
}
then change the body section like this
<body onload='say_hello()'>
<script>
do_conversion();
</script>
<p id="hello">Hello</p>
</body>

Categories

Resources