Auto Insert Tag in Blogger - javascript

I am trying to use jquery to automatically insert "Latest Post" tag to every post published "today."
Here's the code I put in my blogger right before </head>:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
<![CDATA[
var today = new Date();
var date = today.getMonth() + "/" + today.getDate() + "/" + today.getFullYear();
var x = document.getElementsByTagName("abbr").innerHTML;
var NewIn = "\",\"Latest Post"
if (date === x){
$(span.post-labels).append(NewIn);
}
]]>
</script>
I did some search and tried my best to put together the codes. However, it doesn't work and I don't know which steps are wrong. Hope someone can help me out as I am not very good at coding.
Thanks in advance.
#aax Thanks for the help, I'm still trying, but just doesn't work.

The main ideas on how to make this work:
Use $(document).ready(function() { ... } to manipulate the page. If not used, the page might not have been loaded and the manipulation fails.
Date.getMonth is zero-based (e.g. the month of January is represented by 0 and July is 6. When comparing with the blog post date, you need to add 1 to it.
You need to decide for each blog post if it should have the "latest" tag. So you need some kind of loop which checks the date for each blog post and then adds the tag for this post only. In jQuery, use $(<parent element>).find("<sub element selector>") to select a child element of a specific parent.
I tested the following code on your blog:
$(document).ready(function() {
var today = new Date();
var date = (today.getMonth() + 1) + "/" + today.getDate() + "/" + today.getFullYear();
var newIn = $.parseHTML(', Latest Post')
$("div.post").each(function() {
if ($(this).find("a.timestamp-link abbr").text() === date) {
$(this).find("span.post-labels").append(newIn);
}
});
});
According to https://www.w3schools.com/tags/tag_script.asp the script tag should generally look like this:
<script type="text/javascript">
//<![CDATA[
...
//]]>
</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>

use JavaScript to make a webpage that forwards to a URL which includes the date?

I wanted to make a bookmark that uses today's date in the URL; in other words, when the bookmark is launched, the end of the URL would vary each day. So today's would end in .../2017/1/31 and tomorrow's would end in .../2017/2/1.
I thought it might be easiest to just make a barebones HTML page that includes an inline JavaScript to get current year, month, and date and append it to the main URL (which never changes). Does this make sense? Is there an easier way to accomplish this?
I'm okay with HTML elements, but kind of clueless about JavaScript; I literally copied a snippet from another stackoverflow answer that sounded decent and put it into my head tags as you can see below, and tried to adapt my URL into the ahref link:
<HTML>
<head>
<script>var d=new Date();</script>
</head>
<body>
<a href="http://wol.org?t="+d.getTime()>Continue</a>
</body>
</HTML>
The following will run without need for clicking any buttons:
<HTML>
<head>
<script>
Date.prototype.yyyymmdd = function() { //returns YYYY/MM/DD
var mm = this.getMonth() + 1; // getMonth() is zero-based
var dd = this.getDate();
return [this.getFullYear(),
(mm>9 ? '' : '0') + mm,
(dd>9 ? '' : '0') + dd
].join('/');
};
var date = new Date();
window.location.href = "your.url.com/" + date.yyyymmdd();
</script>
</head>
<body>
</body>
</HTML>
Date function from this answer: https://stackoverflow.com/a/3067896/3803371
Note I usually don't condone modification of native prototypes, but I'm feeling lazy today.
You cannot use javascript expression outside script tag. So you cannot call d.getTime like this. Instead of you can do this:
<a id="c" href="">Continue</a>
<script>
(function() { // wait for window load
var d=new Date();
var a = document.getElementById("c");
a.href = "http://wol.org?t="+d.getTime();
})();
</script>
There's a couple problems with your code. First, you're mixing HTML and JavaScript. JavaScript can only go between the <script> tags. Also, the script needs to go below your link you want to modify.
If you want to get the date in the form year/month/day you'll have to do some modification to the date string you get back from your Date object. What I do below is basically get the date string and split it by / into an array. I know the first index is the month, second is the day, and third gives me the year. I store each of those into a variable to use and rearrange later.
I then had to locate the <a> element using getElementById() and then I changed the href value using my date variables.
var dateString = new Date().toLocaleDateString();
var dateArray = dateString.split('/');
var month = dateArray[0];
var day = dateArray[1];
var year = dateArray[2];
var dateOrder = year + "/" + month + "/" + day;
console.log(dateOrder);
var a = document.getElementById('link');
a.href += dateOrder;
<a id="link" href="http://wol.org?t=">Continue</a>
<script>
// Javascript from above goes here
</script>

Use External JavaScript file to change display on div

I am currently doing this:
<div id="textChange" style="display:none;">Blah blah</div>
<script type="text/javascript">
var d = new Date();
var funnyDate = (d.getFullYear() + "" + (d.getMonth()+11) + "" + (d.getDate()+10));
if((funnyDate>=20131916) && (funnyDate<=20131923))
{
document.getElementById("textChange").style.display ="block";
}
</script>
and would like to move the script to an external JS file. How do I do that? I doesn't seem to be working for me.
Thanks.
Include this script after your #textChange div and it will work. For example before closing </body> tag:
...
<script src="funny-script.js" type="text/javascript"></script>
</body>
This is the simplest method. You could also run this code on DOMContentLoaded or window.onload events, but looking at what your script doing I don't think it makes sence.
1-open notepad or notepad ++ or whatever you use as a text editor.
2-copy the javascript code to the text editor without and tags
var d = new Date();
var funnyDate = (d.getFullYear() + "" + (d.getMonth()+11) + "" + (d.getDate()+10));
if((funnyDate>=20131916) && (funnyDate<=20131923))
{
document.getElementById("textChange").style.display ="block";
}
3-save the files with any name you want and don't forget to add the .js extension to the file for example save the file as "test.js"
4-copy the "test.js" to the same directory as html page.
5-add this line to the html page
<script type="text/javascript" language="javascript" src="test.js"></script>
One way to do this is to create a function and include this in a js file
function style_changer(){
var d = new Date();
var funnyDate = (d.getFullYear() + "" + (d.getMonth()+11) + "" + (d.getDate()+10));
if((funnyDate>=20131916) && (funnyDate<=20131923))
{
document.getElementById("textChange").style.display ="block";
}
}
Now in your html give reference to the js file containing this function for example
<script type="text/javascript" src="yourscriptfilename.js" />
you can include this in your section and should work
Save the a file called script.js with the contents.
var d = new Date();
var funnyDate = (d.getFullYear() + "" + (d.getMonth()+11) + "" + (d.getDate()+10));
if((funnyDate>=20131916) && (funnyDate<=20131923))
{
document.getElementById("textChange").style.display ="block";
}
And place this tag inside your HTML document. Place it just before the </body> so you'll know that the element textChange will exist in the DOM before your script is loaded and executed.
<script type="text/javascript" src="script.js" />
Make sure that script.js is in the same directory as your HTML document.
put this below code in a function
step1:
function onLoadCall()
var d = new Date();
var funnyDate = (d.getFullYear() + "" + (d.getMonth()+11) + "" + (d.getDate()+10));
if((funnyDate>=20131916) && (funnyDate<=20131923))
{
document.getElementById("textChange").style.display ="block";
}
}
Step2:-
call that function on page load
<body onload='onLoadCall()'>
...
</body>
step3:-
now move the script to another file it will work
Put script in a separate file and name it yourScript.js and finally include it in your file
add the code within the script file
function changeFunnyDate(){
var d = new Date();
var funnyDate = (d.getFullYear() + "" + (d.getMonth()+11) + "" + (d.getDate()+10));
if((funnyDate>=20131916) && (funnyDate<=20131923))
{
document.getElementById("textChange").style.display ="block";
}
}
Finally add the script in your file & call the method
<script src="yourScript.js" type="text/javascript"></script>
Take everything between your script tags and put it in another file. You should save this file with a .js file extension. Let's pretend you save it as textChange.js.
Now the simplest thing to do would be to include the script file just after your <div> tag -- so basically where the <script> tags and code were before, write:
<script type="text/javascript" src="textChange.js"></script>
This assumes that 'textChange.js' is in the same folder as your HTML file.
...
However, that would far too easy! It is generally best practice to place <script> tags in the <head> of your HTML file. You can move the line above up into the head but then the script will load before your <div> does--it will try to do what it does and it will fail because it can't find the div. So you need to put something around the code in your script file so that it only executes when the document is ready.
The simplest way to do this (and there may be better ways) is write the following...
window.onload = function () {
var d = new Date();
var funnyDate = (d.getFullYear() + "" + (d.getMonth()+11) + "" + (d.getDate()+10));
if ((funnyDate>=20131916) && (funnyDate<=20131923))
{
document.getElementById("textChange").style.display ="block";
}
}
This will mean your script is in the head where it should be and that it only performs when your whole page is ready, including the div that you want to act on.
Hope this helps.

Redirecting using cookies

I've made a web site, and on my index page there are two links. One leads to /eng/index.htm and second to /hr/index.htm. I've also added a "Switch to" option on every /eng/ page and every /hr/ page to switch to other language.
I'm trying to make cookie that remembers users choice and next time he goes to index page it redirects him to the index page of the language he has chosen the first time.
And also if it's possible to change to cookie if users has clicked on "Switch to" link.
I've tried with many java scripts and suggestions from this site but no luck. :(
I've added this to my language index pages:
<script language="JavaScript" type="text/javascript">
var d = new Date()
var dMonth = d.getTime() + 30*24*60*60*1000
d.setTime(dMonth)
document.cookie = 'startPage=' + location.href + '; expires=' + d.toGMTString()
function deleteCookie(){
var d = new Date(2000,1,1)
document.cookie = 'startPage=' + location.href + '; expires=' + d.toGMTString()
}
</script>
And this to my index page:
<script language="JavaScript" type="text/javascript">
var c = document.cookie.split(';')
if(c.length >0){
for(m=0;m<c.length;m++){
if(c[m].indexOf('startPage')>-1){
location.replace(c[m].split('=')[1])
}
}
}
</script>
you need to add domain=example.com; too your cookie, because you will be setting it on the second page, but reading it on the index page. To make switch to thing work, just run your delete cookie function and create a new one with the corresponding url.

eclipse jsp formatter - inserts linebreaks in <script>

I recently upgraded to eclipse indigo from galileo. There has been some changes in the default formatter in my jsp pages.
<script type="text/javascript">
var DAY = '<%=Constants.SALES_DAY%>';
var WEEK = '<%=Constants.SALES_WEEK%>';
var MONTH = '<%=Constants.SALES_MONTH%>';
var YEAR = '<%=Constants.SALES_YEAR%>';
</script>
Ctrl-Shift-F on the file produces:
<script type="text/javascript">
var DAY = '<%=Constants.SALES_DAY%>';
var WEEK = '<%=Constants.SALES_WEEK%>';
var MONTH = '<%=Constants.SALES_MONTH%>';
var YEAR = '<%=Constants.SALES_YEAR%>
';
</script>
which breaks the page when deployed. Where and how can I modify the setting responsible for this behavior?
found this post which helped and got info here.
http://www.eclipse.org/forums/index.php/m/769392/#msg_769392
looks like an eclipse bug.

Categories

Resources