Date display with javascript - javascript

my instructions are to Include a function defined via a function
expression that displays the current date and time in an h2 at the top of the
page when the page is opened. Add an id=”dateDisplay” to the h2. Include
a self-invoking function that changes the color of the date text that was
printed by the first function.
Im a bit confused on how to accomplish this. I tried to do a function expression to display the date but i get nothing shown and no errors. I tried to do a body onload to call the function but that result in a console error of function not defined.
HTML
<div>
<h2 id="dateDisplay"></h2>
</div>
Javascript
var d = new Date();
var x = function dateDisplay(){
document.getElementById("dateDisplay").value = d;
}
I'm really confused by the instructions. What exactly am I suppose to do to get this in working order.
edited: I had an error with my link to my js file. The issue now is I get console error document.getElementById... is null weather i use innerHTML or value or .innerText

You need to call your function, and use .innerText and not .value. Note value is only for input elements.
var d = new Date();
var x = function dateDisplay(){
document.getElementById("dateDisplay").innerText = d;
}
x();

You can also use the .innerHTML method like so:
var d = new Date();
var x = function dateDisplay(){
document.getElementById("dateDisplay").innerHTML = d;
}
x();
You also forgot to call the function x

you must use this code :
Javascript:
var d = new Date();
var x = function dateDisplay(){
document.getElementById("dateDisplay").innerHTML = d;
}
x();
To "display data" in HTML, (in most cases) you will set the value of an innerHTML property.after this change you must call x() function .
and you hava to use this after dateDisplay element loaded.

call function directly more prefer than assign to variable function
var d = new Date();
dateDisplay();
function dateDisplay(){
document.getElementById("dateDisplay").innerHTML = d;
}

Related

Split php varibale with JS into array

I have tried everything and I can not split a PHP variable into two parts so I can insert them into two input fields. I have read numerous topics here and I don't see the problem...
This peace of code gives me a result that php variable is inserted into a wanted filed.
Lets say the PHP variable is data1-data2:
document.hiderad.selectstate.onchange = updateText;
function updateText() {
var str = document.hiderad.selectstate;
document.hiderad.opis.value = str.value;
}
Code above inserted data1-data2 into wanted HTML input.
And soon as i try to split it i get undefined warning. I have tried 7 different things to approach this problem so i want even list all the versions I tried. Can someone please help?
document.hiderad.selectstate.onchange = updateText;
function updateText() {
var str = document.hiderad.selectstate;
var array = str.toString().split('-');
a = array[0], b = array[1];
document.hiderad.opis.value = a.value;
document.hiderad.iznos.value = b.value;
}
Code above gives me b undefined if i remove last line i get a undefined.
You shouldn't be using a.value and b.value, that's for getting the value of an input field, not a string. You should use that to get the value of the selectstate input.
Also, always declare local variables unless you have a specific reason to assign global variables.
function updateText() {
var str = document.hiderad.selectstate;
var array = str.value.split('-');
var a = array[0], b = array[1];
document.hiderad.opis.value = a;
document.hiderad.iznos.value = b;
}

javascript variable shows in console.log but not in browser output

I am trying to reuse the output of the year variable.
I will need to reuse the updated value [based on hashchange] in multiple functions later on.
It displays the correct value in the browser console, but it doesn't display in the browser.
<html>
<body>
<p></p>
1
2
</body>
<script>
location.hash = '#2019';
showHash();
var p = document.querySelector('p');
p.innerHTML = window.year;
function showHash() {
return year = location.hash;
}
window.onhashchange = showHash;
</script>
</html>
By assigning location.hash to year you are not modifying p.innerHTML. year and p.innerHTML are not referencing each other's value. When you initialised as follows:
p.innerHTML = window.year;
The value of year was copied so now you have two values which happen to be the same at that moment, but they are not linked so that if you would assign a new value to the one, it would also update the other. No, they are not references.
So in the event handler you should also assign the new hash to p.innerHTML, or better -- as the hash is text -- assign it to p.textContent:
var p = document.querySelector('p');
var year;
function showHash() {
// Assign both to textContent and year (they are independent)
p.textContent = year = location.hash;
// Maybe call some other functions which need to know about `year`
manage();
}
function manage() {
console.log(year);
// ... etc
}
window.onhashchange = showHash;
location.hash = '#2019'; // This triggers showHash, no need to call it explicitly
<p></p>
1
2

Why does this Javascript function not work if called twice?

The Jasmine (unit?) tests I'm running works for all test with my code below, but the last test calls Gigasecond.date() twice, then validates the second one, which fails.
var Gigasecond = function(date) {
this.startDate = date;
};
Gigasecond.prototype.date = function() {
var x = this.startDate;
x.setSeconds(x.getSeconds() + 1000000000);
return x;
}
module.exports = Gigasecond;
I guess I don't know why this fails. When I log to the console I see the date gets incremented twice, but thought that x is its own separate variable that gets created/destroyed each time the function is called.. but it seems not. Is x just a reference to the actual .startDate field on the object? Is there any reference material for how this works? I looked around but couldn't find anything that applies to what's happening in this code.
You state that you
thought that x is its own separate variable that gets created/destroyed each time the function is called.. but it seems not. Is x just a reference to the actual .startDate field on the object?
That is correct. Dates are objects, and in JavaScript, objects are assigned to variables by reference, not copy. If you intend to work with a copy, you need to return a clone of the Date object with new Date(dateToBeCopied.getTime()) first.
In your code, if you want to work on a copy of the date, you need to replace the line
var x = this.startDate; //assignment by reference
with this line
var x = new Date(this.startDate.getTime()); //assignment by copy
The example code below demonstrates how this works. The Date Object dateA is assigned to the variable refA by reference and to the variable copyA by copy. When modifying refA, this affects dateA, whereas copyA is unaffected.
var dateA = new Date();
//assign a reference to dateA
var refA = dateA;
//assign a copy of dateA
var copyA = new Date(dateA.getTime());
//modify refA, increment with one year
refA.setFullYear(refA.getFullYear() + 1);
//variable refA points to dateA,
//both show the date incremented with one year
console.log('+1 year: ', dateA);
console.log('+1 year: ', refA);
//variable copyA returns an unmodified copy,
//not incremented
console.log('unmodified copy: ', copyA);

javascript can't use input to grab an object property

So i've got this code below (all javascript). And I wish to grab the votecount for a game on user input
function Game(gamename,votes) {
this.gamename = gamename;
this.votes = votes;
};
var lol = new Game("League of Legends",1100);
var dota = new Game("DOTA 2",2100);
var ql = new Game("Quakelive",3100);
var csgo = new Game("Counter Strike: GO",4100);
function PostVotes(gnshort){
//string names - working
console.log(gnshort + 'name');
console.log(gnshort + 'votes')
var CalcVotes = function(gnshort){
var votecount = gnshort.votes;
console.log(votecount);
}
CalcVotes(gnshort);
//CalcVotes(lol); //works
};
PostVotes('lol');
I keep getting the error undefined when calling CalcVotes(gnshort). and I know it's not the function it's passing the lol as gnshort it's asif it's reading as a string instead of a variable or something. I've only been learning javascript for the past week so any advice would be helpful
PostVotes('lol'); will pass lol as a string ('lol' is equivalent to "lol"). What you need to do is simply pass the variable lol like
PostVotes(lol);
And it will return lol.votes, aka 1100.

how to put a custom function in a javascript object for use in a html template?

I'm using this pretty handy JavaScript template library: https://github.com/blueimp/JavaScript-Templates.
I can create elements and add data to them as many are doing with underscore.js and mustache.js.
My problem comes when I want to add my own functions and not just strings to the object that will populate the template's various nodes. What i'd like to do is run the function nicetime() to update the time of my newly inserted <div>'s instead of just showing the time once.
Here's the code, and a full demo.
HTML:
<button data-id="1">1</button>
<div data-id="1"></div>
<div id="time_since"></div>
JS:
$(document.body).on('click', 'button', function(){
var id= $(this).data('id');
var data={id:id, string: "just now...", fxn: nicetime()};
var result = tmpl('<div id="string" data-id="'+id+'">{%=o.string%}</div>
<div id="function" data-id="'+id+'">{%=o.fxn%}</div>', data);
$('div[data-id="'+id+'"]').html(result);
nicetime();
});
function nicetime(){
var time = new Date();
var comment_date = setInterval(function() {
var time2 = time_since(time.getTime()/1000);
$('#time_since').html(time2);
return time2;
},
1000);
}
note: inside nicetime() there is a function time_since() which is available on the jsfiddle. It is for formatting the date like this: "1 second ago...".
In javascript functions are objects just like any other variable.
Your problem is that you are invoking the function instead of assigning it to a property.
var data={id:id, string: "just now...", fxn: nicetime()};
instead use only the function name (without the parenthesis)
var data={id:id, string: "just now...", fxn: nicetime};
EDIT
Actually I would take a different approach anyway. Instead of using a timer, just invoke the method as you previously were:
var data={id:id, string: "just now...", fxn: nicetime(this)};
$('div[data-id="'+id+'"]').html(result);
nicetime(this);
I modified nicetime to take the element that tracks the time (i assumed there was a button for each node (otherwise the data would be stored on each node)
function nicetime(el){
var time = $(el).data('start') || new Date();
var time2 = time_since(time.getTime()/1000);
$('#time_since').html(time2);
var comment_date = time2; //still need to figure out where to put this value
$(el).data('start', time)
return comment_date;
}

Categories

Resources