This question already has answers here:
Load scripts inside innerHTML [duplicate]
(2 answers)
Closed 4 years ago.
I have an HTML page that loads within another HTML page via innerHTML. After several days of work, this script works fine and another JS file is called for the interior page, a file (named "Unified_app.js") that basically runs some date calculations. Everything is working fine and the correct dates print to the console. However, I can't figure out on the page within a page can display the console dates. Document.write does not work in this situation (I'm assuming because of the tags are not read properly?), so I need to come up with a workaround. Any ideas?
This is the innerHTML functions as I have them:
function getYearOffset(strCutoffDate, intYearOffset)
{
var datCurrentDate = new Date();
var intCurrentYear = datCurrentDate.getFullYear();
var intCurrentMonth = strCutoffDate.substr(5, 2) - 1;
var intCurrentDay = strCutoffDate.substr(8, 2);
var datCutoffDate = new Date(intCurrentYear, intCurrentMonth, intCurrentDay);
if (Number(datCurrentDate) < Number(datCutoffDate))
{
var datRequestedDate = new Date(datCurrentDate.getFullYear(), intCurrentMonth, intCurrentDay);
}
else
{
var datRequestedDate = new Date(datCurrentDate.getFullYear() + intYearOffset, intCurrentMonth, intCurrentDay);
}
return datRequestedDate.getFullYear();
}
var script = document.createElement("script");
script.src = "/resource/resmgr/scripts/Unified_app.js";
document.head.appendChild(script);
function getInclude(strIncludeContainer, strIncludeURL)
{
var strPage = '';
var intIndexOfBodyOpen = 0;
var intIndexOfBodyClose = 0;
var objXhttp;
objXhttp = new XMLHttpRequest();
objXhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
strPage = this.responseText;
intIndexOfBodyOpen = strPage.indexOf('<body>');
intIndexOfBodyClose = strPage.indexOf('</body>');
document.getElementById(strIncludeContainer).innerHTML = strPage.substring(intIndexOfBodyOpen + 6, intIndexOfBodyClose);
}
};
objXhttp.open("GET", strIncludeURL, true);
objXhttp.send();
}
I'm using:
<script>document.write(award_year1);</script>
to write the following date calls:
const date = new Date();
let offset = 0;
const threshold = new Date();
threshold.setMonth(3); //January is 0!
threshold.setDate(3);
if (Date.now() > threshold) {
offset = 1;
}
var theDate = new Date();
var award_year1 = date.getFullYear() + offset;
var award_year2 = date.getFullYear() + 1 + offset;
console.log(award_year1);
console.log(award_year2);
When loading the page-within-a-page HTML file or the interior page itself I get the correct date calculations sent to the console, but I can't seem to get them to print within the innerHTML page when loaded into the other page. Any ideas you could send me down the right path? This is probably beyond my level of understanding of JavaScript. I thought perhaps my code was not in the correct order but I've been fiddling with this and can't seem to figure out where or why.
I'm not sure if this will solve the problem but you can try it.
As you said the document.write will not be triggered cause your JS is loaded before your DOM is.
document.addEventListener("DOMContentLoaded", function(event) {
//your functions
});
Maybe this will help you out
I guess this is just not possible. I ended up replacing the innerHTML with an iframe and that seems to have worked so that I can now use script tags. Not an ideal solution but it works
Related
I am currently learning JavaScript through some tutorials and this example came out in the tutorial.
I'm just confused why must the if statement be there.
I tried erasing the if statement and it still worked. Can someone help me please.
var timesVisited=0;
var dateVisited = 'Never';
if(localStorage.myLastVisit){
var visit = JSON.parse(localStorage.myLastVisit);
timesVisited = visit.numVisits;
dateVisited = visit.dateVisits;
}
$("#dateVisit").html(dateVisited);
timesVisited++;
$("#numVisit").html(timesVisited);
var myVisits = {};
myVisits.numVisits = timesVisited;
var d = new Date();
var hours = d.getHours();
var minutes = d.getMinutes();
myVisits.dateVisits = hours + ':' + minutes;
localStorage.myLastVisit = JSON.stringify(myVisits)
I tried erasing the if statement and it still worked.
Only if myLastVisit is already in localStorage. If it isn't there (which is what the if is testing for), without the if you'll get an error from JSON.parse because you'll pass undefined into it, which will get converted to a string with the charactersundefined in it because JSON.parse requires a string, which will then fail because that's not valid JSON. The if is there so that if the setting isn't present, the default values assigned to timesVisited and dateVisited are used.
Works if the setting is there:
var timesVisited=0;
var dateVisited = 'Never';
var visit = JSON.parse(`{"numVisits": 2, "dateVisits": "2020-03-27"}`);
timesVisited = visit.numVisits;
dateVisited = visit.dateVisits;
console.log(timesVisited); // 2
console.log(dateVisited); // "2020-03-27"
Fails if it isn't:
var timesVisited=0;
var dateVisited = 'Never';
var visit = JSON.parse(undefined); // ERROR
timesVisited = visit.numVisits;
dateVisited = visit.dateVisits;
console.log(timesVisited);
console.log(dateVisited);
I have built a tool for timing indirect workers, it consists of a start and stop button which both place a time stamp into the google sheet and then calculates the difference to record a time. It works great however when I share it with some people it does not allow them to use it saying that they do no have access to run the script. If they open script editor they can manually run it however that will no fly because I will be sending this out to approximately 50 people.
Here is the code and start and stop are two different scripts. Please let me know if I am missing something and I appreciate the help. Thanks
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var start = new Date();
function StartScript() {
var last = ss.getLastRow();
ss.getRange(last+1,1).setValue(last+1)
var source = ss.getRange(last+1,1).getValue();
source = Number(source);
if (source <= 16) {
ss.getRange(last+1,2).setValue(start);
}
else {
ss.getRange(last+1,2).setValue("Stop Timing");
}
}
function stop() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var date = new Date();
var last1 = ss.getLastRow();
ss.getRange(last1, 3).setValue(date);
var lastrow = ss.getLastRow()
ss.getRange("D" + (lastrow)).setFormula("=C" + (lastrow) + "-B" + (lastrow));
}
This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 5 years ago.
Hey guys, I have this quite simple script which works great on chrome & firefox.
The idea is to nab "choice" value from the URL and proceed with the script. As mentioned other browsers work fine, but IE seems to have trouble with it.
Does anyone know a workaround? I don't want to just run the function on the previous page.
var url1 = "https://www.youtube.com";
var url2 = "http://ign.com";
function jukebox()
{
let params = (new URL(document.location)).searchParams;
let choice = params.get("choice");
if ( choice == 1 )
{
window.location=(url1);
}
else if ( choice == 2 )
{
window.location=(url2);
}
}
jukebox();
redirect();
IE does not support searchParams but you could try writing your own parse function:
var params = {};
var str = document.location;
var start = str.indexOf("?");
document.write(start+"<br>")
start += str.slice(start).indexOf("choice=") + 7;
var end = start + str.slice(start).indexOf("&") + 1;
if (!end) end = str.length
var choice = str.slice(start, end);
I have an .innerHTML statement that isn't working correctly, but only while within an if statement.
document.getElementById("music").innerHTML = "[MUSICPLAYERCODE]";
is the code that I'm using, and it's within this.
<script type="text/javascript">
var thedate - new Date();
var hourofday = thedate.getHours();
if(hourofday == 0) {
document.getElementById("music").innerHTML = "[MUSICPLAYERCODE]";
}
</script>
While outside of the if statement, the code works completely fine, however, inside the if statement it refuses to work. Even if I change the condition to just a plain true, the code still will not execute. I'm new to javascript, and I can't seem to find any error after looking for a couple hours. If it helps at all, the music player I'm using is at Billy Tumblr Audio Player.
I think you have added not just the if condition but also the code related to date calculation.
There you have a syntax error, used - instead of =. In your browser console you should see an error like Uncaught SyntaxError: Unexpected token -
var thedate = new Date();
// ^ = not -
var hourofday = thedate.getHours();
if (hourofday == 0) {
document.getElementById("music").innerHTML = "[MUSICPLAYERCODE]";
}
var thedate - new Date(); ?
Change it to:
var thedate = new Date();
You can try like this.
window.onload=function(){
var thedate = new Date();
var hourofday = thedate.getHours();
if(hourofday == 0) {
document.getElementById("music").innerHTML = "<H1>[MUSICPLAYERCODE]</H1>";
}
};
I have a jquery function which adds tag to first row of table.
I tried using append, however its not working, so i got a solution which is very slow and it somehow gives error "Script on this page is causing internet explorer run slow..."
Function is as
jQuery.fn.fixGridView = function () {
"use strict";
// var start = +new Date(); // log start timestamp
if (jQuery(this).is('table') && this.find('thead').length === 0) {
var theadv = "<thead><tr>" + this.find('tbody tr:first').html(); +"</tr></thead>";
this.find('tbody tr:first').remove();
var htmlv = this.html();
this.html(theadv + htmlv);
}
//var end = +new Date(); // log end timestamp
// var diff = end - start;
// alert(diff);
return this;
};
Can anybody help me to make this code run faster?
EDIT: I have to use IE..that is the requirement (ie8).
Edit2: I have created js fiddle: http://jsfiddle.net/4xLzL/
To increase rendering performance you must understand that DOM manipulation (including reflows & repaints) are expensive operations. Your code currently re-creates the entire table with the <thead> added the majority of the <tbody> content remains the same. This massive "redraw" of the table is highly inefficient. Especially when in IE 8, where rendering tables is extra slow, you have to modify the DOM as little as possible.
I've refactored your logic to minimize the number of lookups performed to find elements by saving them to a variable to be re-used. Also, removed the .html('...') call that re-renders the table, but instead used the .prepend() function to add the <thead> into the <table> as the first child.
jQuery.fn.fixGridView = function () {
"use strict";
var start = +new Date(); // log start timestamp
if (this.is('table') && this.children('thead').length === 0) {
var firstRow = this.children('tbody').children('tr:first');
var thead = "<thead><tr>" + firstRow.html() + "</tr></thead>";
firstRow.remove();
this.prepend(thead);
}
var end = +new Date(); // log end timestamp
var diff = end - start;
alert(diff);
return this;
};
$(document).ready(function () {
$('table[id*="gvCategories"]').fixGridView();
});
Go ahead and test it in IE8: http://jsfiddle.net/amyamy86/4xLzL/7/
The problem is not with the plugin, but with your selector. You only want tables, so modify your selector to be as follows.
$('table [id*="gvCategories"]').fixGridView();
I also updated the fiddle.