Use External JavaScript file to change display on div - javascript

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.

Related

How can I load script tags from a string?

An external source is providing the content of the script tags written as HTML in a string.
I need to add these script tags into the head.
If I do it like this, all script tags are added to the DOM in head tag, however none of the sources are actually being loaded (devtools network tab).
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<script>
let sLoadThis = '<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/underscore#latest/underscore-umd-min.js">'
sLoadThis = sLoadThis + "<" + "/script>"
let oScript = $(sLoadThis).get(0);
document.head.appendChild(oScript);
</script>
</body>
</html>
If I sort of use the jQuery as an interpreter to then insert the script tag with vanilla JS, it works:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<script>
let sLoadThis = '<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/underscore#latest/underscore-umd-min.js">'
sLoadThis = sLoadThis + "<" + "/script>"
let oScript = $(sLoadThis).get(0);
var vanillaScript = document.createElement('script')
vanillaScript .type = 'text/javascript'
vanillaScript .src = oScript.src
document.head.appendChild(vanillaScript )
</script>
</body>
</html>
I would like to understand why it doesn't work in my first example.
The second example runs because you 're using a dom node. That 's how appendChild() works. The jQuery get() method works with existing dom elements. The only thing you 've got is a string, that does not exist in your dom yet. Try the following.
let script = $.parseHtml(sLoadThis);
console.log(script.get(0)); // should be a script dom node element
document.head.appendChild(script.get(0));
In vanilla JavaScript its even easier and much more faster than jQuery because you don 't have to use a dependency.
const fragment = document.createRange().createContextualFragment(htmlStr);
document.head.appendChild(fragment);
As far as I know there are 4 ways to create a DOM element from a string:
OPTION 1: innerHTML
OPTION 2: insertAdjacentHTML
OPTION 3: DOMParser().parseFromString
OPTION 4: createRange().createContextualFragment
HTML5 specifies that a <script> tag inserted with one of the 3 first options should not execute because it could became a security risk. See this
So, in the example, although all script tags are added to the DOM in the <head> section, only the option number 4 will be executed.
const str1 = "<script>alert('option 1 executed')" + "<" + "/script>"
const str2 = "<script>alert('option 2 executed')" + "<" + "/script>"
const str3 = "<script>alert('option 3 executed')" + "<" + "/script>"
const str4 = "<script>alert('option 4 executed')" + "<" + "/script>"
// OPTION 1
const placeholder1 = document.createElement('div')
placeholder1.innerHTML = str1
const node1 = placeholder1.firstChild
document.head.appendChild(node1)
// OPTION 2
const placeholder2 = document.createElement('div')
placeholder2.insertAdjacentHTML('afterbegin', str2)
const node2 = placeholder2.firstChild
document.head.appendChild(node2)
// OPTION 3
const node3 = new DOMParser().parseFromString(str3, 'text/html').head.firstElementChild
document.head.appendChild(node3)
// OPTION 4
const node4 = document.createRange().createContextualFragment(str4)
document.head.appendChild(node4)

Auto Insert Tag in Blogger

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>

iframe onload with src not working in IE11

I have a JavaScript program that gets the last modified date of a txt file. The code works fine in Firefox but for some reason, it does nothing in IE11. My code is listed below.
JavaScript code:
function getLastMod(){
var myFrm = document.getElementById('myIframe');
var lastMod = new Date(myFrm.contentWindow.document.lastModified);
var getSpan = document.getElementById('LastModified');
getSpan.innerHTML += "<font color=red> (File Last Updated: " + lastMod.toLocaleString() + ")</font>";
}
HTML code:
<span id="LastModified"></span>
<iframe id="myIframe" onload="getLastMod()" src="date.txt" style="display:none;"></iframe>
I had a similar issue when I tried to define the event in the tag. I had better results assigning the event from within javascript.
<script type="text/javascript">
document.getElementById('myIframe').onload = function() {
getLastMod();
}
</script>

Change document.write synchronously to something asynchronously?

I'm trying to switch out some old HTML that uses document.write to prevent a remote website hanging if script.js doesn't load right away. I have access to script.js to change it.
My example code:
<script language="JavaScript">
var foo1 = "test 1";
var foo2 = "test 2";
document.write('<script src="script.js?id=' + foo1 + '&num=' + foo2 + '"><\/script>');
</script>
Example of script.js output.
document.write("<a href='http://example.com/file.php?id=123' title='title'>some data</a>")
How would I go about making my above code load asynchronously?
Update:
I found a snippet of code that I believe will do the trick.
<script>
var script = document.createElement('script');
script.src = "script.js";
document.getElementsByTagName('head')[0].appendChild(script);
</script>
I just don't understand what to put in script.js to make the snippet of code above work with my output example earlier. What should be on script.js for the snippet of code above to work?
I am not exactly sure what I are you trying to accomplish, but something like this in script.js might work:
document.getElementsByTagName('body')[0].innerHTML = "<a href=..>Something</a>";
Update: (+1 for Sam contribution)
document.getElementsByTagName('body')[0].innerHTML += "<a href=..>Something</a>";
Update: (place at beginning of the page)
document.getElementsByTagName('body')[0].innerHTML = "<a href=..>Something</a>" + document.getElementsByTagName('body')[0].innerHTML;
Update: (place at current position of script)
var p = document.createElement("p");
p.innerHTML = "aaa";
var scripts = document.getElementsByTagName('script');
var current = scripts[scripts.length - 1];
current.parentNode.insertBefore(p, current);
http://jsfiddle.net/ekohfq5h/

Beginner HTML5 path/to/jsFile. Unable to load script?

I'm having some trouble running some JS inside a html5 body.
Here's what's happening, whenever I remove all instances of the arrays from the JS file I am using, the script loads fine in the index file, however, when I add src to the attribute and/or mention an array name from said file, it breaks. simple as that.
since I'm planning on making a pretty big site, I have already begun organizing my root.
here's a little demo:
rootFolder/
index.htm
js/targetJS.js
here's the code
<script src="js/targetJS.js" type="text/javascript">
document.writeln("<table id='services' class='services' name='services'>");
document.writeln("<tr>");
document.writeln("<th> Preview: </th>");
document.writeln("<th> Description: </th>");
document.writeln("<th> Cost: </th>");
document.writeln("</tr>");
var i = 0;
//for ( i = 0; i < servicePrev.length; i++)
{
if (i % 2 == 0){
document.writeln("<tr class='even' id='even'>");
}
else{
document.writeln("<tr class='odd' id='odd'>");
}
//document.writeln("<td> " + servicePrev[i] + " </td>");
//document.writeln("<td> " + serviceDesc[i] + " </td>");
//document.writeln("<td> " + serviceCost[i] + " </td>");
document.writeln("</tr>");
}
document.writeln("</table>");
</script>
Whenever i add the src in the attribute and the lines that are commented out, the code does not work, however, when I omit the src and the lines that are currently commented out, the code works fine. even JSfiddle reports it working fine.
The contents of the JS file are 3 arrays with 5 indexes.
You need to seperate your tags
<script type="text/javascript" src="awesomescript.js"></script>
and
<script>
// some awesome code here
</script>
Since html5, you are free to name <script type="text/javascript"> or just use <script> for javascript, as text/javascript is default.
Quoted from http://javascript.crockford.com/script.html
The script tag has two purposes:
It identifies a block of script in the page. It loads a script file.
Which it does depends on the presence of the src attribute. A
close tag is required in either case.
The src attribute is optional. If it is present, then its value is a
url which identifies a .js file. The loading and processing of the
page pauses while the browser fetches, compiles, and executes the
file. The content between the and the
should be blank.
So, the script file should be loaded by dedicated script tag without content, the script content should be inserted into another script tag, after all if you have other errors you can check in the console of your broswer
<script src="js/targetJS.js" type="text/javascript"></script>
<script type="text/javascript">
document.writeln("<table id='services' class='services' name='services'>");
document.writeln("<tr>");
document.writeln("<th> Preview: </th>");
document.writeln("<th> Description: </th>");
document.writeln("<th> Cost: </th>");
document.writeln("</tr>");
var i = 0;
//for ( i = 0; i < servicePrev.length; i++)
{
if (i % 2 == 0){
document.writeln("<tr class='even' id='even'>");
}
else{
document.writeln("<tr class='odd' id='odd'>");
}
//document.writeln("<td> " + servicePrev[i] + " </td>");
//document.writeln("<td> " + serviceDesc[i] + " </td>");
//document.writeln("<td> " + serviceCost[i] + " </td>");
document.writeln("</tr>");
}
document.writeln("</table>");
</script>

Categories

Resources