I have JS code in both the body and head portions of my page. If I wanted to have them be in an external .js file, how would I move them over and then call them back onto the page?
Head -
<script language="Javascript">
setInterval("settime()", 1000);
function settime () {
var curtime = new Date();
var curhour = curtime.getHours();
var curmin = curtime.getMinutes();
var cursec = curtime.getSeconds();
var time = "";
if(curhour == 0) curhour = 12;
time = (curhour > 12 ? curhour - 12 : curhour) + ":" +
(curmin < 10 ? "0" : "") + curmin + ":" +
(cursec < 10 ? "0" : "") + cursec + " " +
(curhour > 12 ? "pm" : "am");
document.date.clock.value = time;
}
</script>
Body -
<script language="JS" type="text/javascript">
var monthArray = new Array("January", "February", "March", "April", "May",
"June", "July", "August", "September",
"October", "November", "December");
var today = new Date();
var todayMonth = today.getMonth();
var todayDate = today.getDate();
var todayYear = today.getFullYear();
document.write(monthArray[todayMonth] + " " + todayDate + ", " + todayYear);
</script>
Move your JS code into an external file (say, my.js) and include it within your page as :
<script type="text/javascript" src="my.js"></script>
Of course, the above assumes that my.js lies in the same folder/directory as your page. you'll need to adjust the src value as per the location of you JS file.
Related
<!DOCTYPE>
<html>
<head>
<script>
function displayDate() {
var date = new Date();
const monthArray = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const dayArray = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
var Date = date.getDate();
var month = monthArray[date.getMonth()];
var year = date.getFullYear();
var day = dayArray[date.getDay()];
var hours = date.getHours() % 12;
var minutes = date.getMinutes();
var amPm = "AM";
if (hours < 10) {
hours = "0" + hours;
}
if (date.getHours() > 12) {
amPm = "PM";
}
var str = Date + " " + month + " " + year + " " + day + " " + hours + ":" + minutes + " " + amPm;
document.getElementById("date1").value = str;
}
</script>
</head>
<body>
Current date: <input id="date1" type="text" size="30" onload="displayDate()">
</body>
</html>
Hi guys, I am trying to display the current date in the textbox. However, I can't seem to get it to work. When the program ran, the textbox did not display anything. I tried using a console.log function to print the output in the console but it didn't seem to work as well. Kindly advise for a solution, thank you.
You can remove the onload() and simply call your function when the window loads.
Something like that:
document.addEventListener("DOMContentLoaded", function() {
displayDate();
});
However, your code has a problem you should be aware of. You cannot name a variable with the name "Date" because this causes conflict with Global function Date(). Instead, rename your variable somehow else. I will include my code to show you what I mean.
<!DOCTYPE>
<html>
<head>
</head>
<body>
Current date: <input id="date1" type="text" size="30">
</body>
<script>
function displayDate() {
console.log("hey!");
let date = new Date();
const monthArray = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const dayArray = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
var theDate = date.getDate();
var month = monthArray[date.getMonth()];
var year = date.getFullYear();
var day = dayArray[date.getDay()];
var hours = date.getHours() % 12;
var minutes = date.getMinutes();
var amPm = "AM";
if (hours < 10) {
hours = "0" + hours;
}
if (date.getHours() > 12) {
amPm = "PM";
}
var str = theDate + " " + month + " " + year + " " + day + " " + hours + ":" + minutes + " " + amPm;
document.getElementById("date1").value = str;
}
document.addEventListener("DOMContentLoaded", function() {
displayDate();
});
</script>
</html>
I'm trying to use the current month, year, month-year and day-month in my html page.
This is the javascript I'm using
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var n = new Date();
var y = n.getFullYear();
var m = n.getMonth();
var d = n.getDate();
document.getElementById("date").innerHTML = d + " " + months[m] + " " + y;
document.getElementById("month-year").innerHTML = months[m] + " " + y;
document.getElementById("day-month").innerHTML = d + " " + months[m];
document.getElementById("year").innerHTML = y;
document.getElementById("month").innerHTML = months[m];
document.getElementById("day").innerHTML = d;
I'm using an html <a> tag to call the date, month, year etc, as follows
<a id="date"></a>
<a id="month-year"></a>
<a id="day-month"></a>
<a id="year"></a>
<a id="month"></a>
<a id="day"></a>
However it only works when I use <a id="date"></a> somewhere in the page, if I don't use <a id="date"></a> then none of the other tags work.
I've created a jsfiddle to highlight the problem. If you remove <a id="date"></a> from the Html section you'll see the problem I'm referring to.
Thanks to the answer below
Full code can be seen at jsfiddle
It's because your javascript is breaking due to null object on
document.getElementById("date").innerHTML = d + " " + months[m] + " " + y;
You should check whether it exists before setting the innerHTML. For example:
var dateObject = document.getElementById("date");
if (dateObject) dateObject.innerHTML = d + " " + months[m] + " " + y;
I have built a counter that counts (both up and down) the date. I only want to have the counter function run down, and once it hits the current date or later to stop running altogether. Right now it alerts saying the date is reached but continues counting even though it has reached the date.
Here is the JSFiddle for the counter.
Here is the Boolean
if(tDate == eDate) {
alert('Today is the event!');
return false;
// clearTimeout( countDown.prototype.update() );
} else {
counter();
}
Here is the whole code
$(document).ready(function() {
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var d = new Date();
var month = monthNames[d.getMonth()];
var day = d.getUTCDate();
var year = d.getUTCFullYear();
var eMonth = $("#d-month").html();
var eDay = $("#d-day").html();
var eYear = $("#d-year").html();
var tDate = month + " " + day + " " + year;
var eDate = eMonth + " " + eDay + " " + eYear;
alert("today's date: " + tDate + " event's date: " + eDate);
if(tDate == eDate) {
alert('Today is the event!');
return false;
// clearTimeout( countDown.prototype.update() );
} else {
counter();
}
function counter() {
function countDown(initDate, id) {
this.counterDate = new Date(initDate);
this.update();
}
countDown.prototype.calculateUnit=function(secDiff, unitSeconds){
var tmp = Math.abs((tmp = secDiff/unitSeconds)) < 1? 0 : tmp;
return Math.abs(tmp < 0 ? Math.ceil(tmp) : Math.floor(tmp));
}
countDown.prototype.calculate=function(){
var secDiff = Math.abs(Math.round(((new Date()) - this.counterDate)/1000));
this.days = this.calculateUnit(secDiff,86400);
this.hours = this.calculateUnit((secDiff-(this.days*86400)),3600);
this.mins = this.calculateUnit((secDiff-(this.days*86400)-(this.hours*3600)),60);
this.secs = this.calculateUnit((secDiff-(this.days*86400)-(this.hours*3600)-(this.mins*60)),1);
}
countDown.prototype.update=function(){
this.calculate();
$("#countdown-day").html(this.days + (this.days == 1));
$("#countdown-hour").html(this.hours + (this.hours == 1));
$("#countdown-min").html(this.mins + (this.mins == 1));
$("#countdown-sec").html(this.secs + (this.secs == 1));
var self = this;
setTimeout(function(){self.update();}, (1000));
}
function counterInit() {
var month = $("#d-month").html();
var day = $("#d-day").html();
var year = $("#d-year").html();
var time = $("#d-time").html();
new countDown( month + day + "," + year + time);
// new countDown('May 9, 2015, 00:00:00', 'counter'); }
}
counterInit();
}
});
I tried your fiddle and I can tell you there are some blank spaces at the end of each string which makes them differ between each other.
So If you just add these lines it will work
tDate = jQuery.trim(tDate);
eDate = jQuery.trim(eDate);
Here's your fiddle updated
http://jsfiddle.net/c5qkm5gL/
Edit:
I forgot to mention that I changed '.html()' to '.text()', this way you get the plain text instead of the html content.
As an advice, for debugging use console.log instead of an alert.
This question already has answers here:
jQuery - Change 1-24 hour to 1-12 hour using .getHours() method?
(2 answers)
Closed 9 years ago.
I want to change my hours into 12hrs not 24hrs.
this is my code :
$(document).ready(function() {
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var newDate = new Date();
newDate.setDate(newDate.getDate());
$('#Date').html(dayNames[newDate.getDay()] + " " + newDate.getDate() + ' ' + monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear());
setInterval(function() {
var seconds = new Date().getSeconds();
$("#sec").html((seconds < 10 ? "0" : "") + seconds);
}, 1000);
setInterval(function() {
var minutes = new Date().getMinutes();
$("#min").html((minutes < 10 ? "0" : "") + minutes);
}, 1000);
setInterval(function() {
var hours = new Date().getHours();
$("#hours").html((hours < 10 ? "0" : "") + hours);
}, 1000);
});
You are looking for this
newHours = (oldHours) % 12
if (newHours == 0) {
newHours = 12;
}
This is what I have in a script that is pulling events with a Google Calendar API:
var datestring2 = (startJSDate.getMonth() + 1) + "/" + startJSDate.getDate();
After I append this to a list it prints out in the format 12/2 while I want it to print out Friday, Dec 2.
How can I do this? I have looked into date.js but had no luck.
There is no built in function in Javascript that can do that (I presume you are after something like PHP's date() function).
You can certainly roll your own solution as other answers have suggested, but unless you are really against it, date.js is great for this.
You can use the libraries toString() function to get formatted date strings like so:
Date.today().toString("d-MMM-yyyy");
More information can be found in the DateJS API documention.
You need something like:
var months = ['January', 'February', 'March', ...];
var ordinals = {1:'st', 21:'st', 31:'st', 2:'nd', 22:'nd', 3:'rd', 23:'rd'};
var m = startJSDate.getMonth();
var d = startJSDate.getDate();
var s = months[m] + ', ' + s + (ordinals[s] || 'th');
This article has some great examples on printing out dates in javacript
And from there you want something like this
var d_names = new Array("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday");
var m_names = new Array("January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December");
var d = new Date();
var curr_day = d.getDay();
var curr_date = d.getDate();
var sup = "";
if (curr_date == 1 || curr_date == 21 || curr_date ==31)
{
sup = "st";
}
else if (curr_date == 2 || curr_date == 22)
{
sup = "nd";
}
else if (curr_date == 3 || curr_date == 23)
{
sup = "rd";
}
else
{
sup = "th";
}
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
datestring2 = d_names[curr_day] + ", " + m_names[curr_month] + " " + curr_date + sup );
Will give you Thursday, December 1st