Reputation: 225
im making it display the time in javascript but when it returns the time it is always undefined. below is the code
im not really sure why it always returns undefined though.
$('#bar #time').html(hours + ":" + minutes + " " + suffix);
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
//decides if am or pm
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
// shows 0 before the minutes if under 10
if (minutes < 10)
minutes = "0" + minutes
Upvotes: 0
Views: 5093
Reputation: 2793
Not entirely related to your actual question, but $('#bar #time')
is going to be a fairly inefficient jQuery selector. Since IDs are only used once in your document, searching simply for $('#time')
will give you the same result and only require the JavaScript engine to to fire document.getElementById
once rather than twice.
Minor point, but worth mentioning.
Upvotes: 1
Reputation: 8046
$(document).ready(function(){
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
//decides if am or pm
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
// shows 0 before the minutes if under 10
if (minutes < 10)
minutes = "0" + minutes
$('#bar').html(hours + ":" + minutes + " " + suffix);
});
The order in which you print your variables matters,
they were not defined upon printing.
Upvotes: 0
Reputation: 4454
No semicolons here
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
Upvotes: 0
Reputation:
um, if the code is in that order, you just need to put your first line at the end, as hours
, minutes
and suffix
are all undefined at that point. Other than that it should work fine (and does, per chrome console).
Upvotes: 3