I have some js code that has been imported from another file which has a variable in it I want to update in my HTML file. How can I update the variable without pasting the js code into my HTML file?
JS (script.js):
var link = "https://example.com"
var codeBlock = `...some html code... ${link} ...some more html code`;
document.getElementById("div").innerHTML = codeBlock
HTML:
<div id="div"></div>
<script src= "script.js"></script>
<script>
//I want to change this variable
var link = "https://anotherexample.com"
</script>
On line one of your code, you declare link and give it a value.
On line two, you use that value.
You can't change link later on and affect what happened when the value was read and used in the past.
If you want to change the final result, then it is the final result you have to change (i.e. you need to assign a new value to document.getElementById("div").innerHTML).
You are getting the value but not setting it to the variable that the HTML is showing.Is this you are looking for :
var updatedLink = document.getElementById("anotherlink").innerHTML;
var codeBlock = `...some html code... ${updatedLink} ...some more html code`;
document.getElementById("div").innerHTML = codeBlock
<div id="div"></div>
<div id="anotherlink" style="display:none"></div>
<script src= "script.js"></script>
<script>
var link = "https://anotherexample.com";
document.getElementById("anotherlink").innerHTML = link
</script>
Your script is working and the variable is being changed. If you console.log(link) after declaring it again, you'll see the variable has changed. If you're expecting the script to execute again, that won't happen without calling it again.
What you may want to try is iterating through the document looking for something to trigger that statement, for example, links in the document.
const links = document.querySelectorAll('a');
var href = [];
links.forEach(link => href.push(link.href));
var codeBlock = '';
href.forEach(link => {
if (link == "https://stacksnippets.net/anotherexample.com") {
codeBlock = `...some html code... ${link} ...some more html code`;
document.getElementById('div').innerHTML = codeBlock;
}
})
<div id="div">link</div>
Or without checking for a specific URL:
const links = document.querySelectorAll('a');
var href = [];
links.forEach(link => href.push(link.href));
var codeBlock = '';
href.forEach(link => {
codeBlock = `...some html code... ${link} ...some more html code`;
document.getElementById('div').innerHTML = codeBlock;
})
<div id="div">link</div>
Related
I know how to include CSS or JS files using app script in a web script. but that way includes files content on page lode.
My question is it possible to include partial html page inside the currently opened page?
app script to include CSS or JS
/* #Include JavaScript & CSS & HTML-Partial-Views */
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
and I use like this
<?!= include('Css'); ?>
and here is my attempt.
html
<button onclick="getList("users")">show some html content</button>
<div id="users"></div>
<script>
function getList(users){
var listUsers = google.script.run.showHtml(users);
// how to return showHtml result [list of users]
for (var i; i <= listUsers.length; 1++)
{
document.querySelector("#users").innerHTML += <div>listUsers[i]</div>;
}
}
</script>
gs
function users(sheetName, pageName){
// get users from sheet
var ss= SpreadsheetApp.openById("435yh35h45b35nh6hg5bwh455j");
var dataSheet = ss.getSheetByName(sheetName);
var dataRange = dataSheet.getDataRange().getValues();
return dataRange;
}
From one of the code snippets
// how to return showHtml result [list of users]
Try this:
<button onclick="getList('users')">show some html content</button>
<div id="users"></div>
<script>
function getList(users){
var listUsers = google.script.run
.withSuccessHandler((listUsers) => {
let list = '';
for (var i; i < listUsers.length; i++) {
list += `<div>${listUsers[i]}</div>\n`;
}
document.querySelector("#users").innerHTML = list;
})
.showHtml(users);
}
</script>
Changes done
Replaced "users" by 'users'
Added withSuccessHandler with an arrow function as callback.
The arrow function build a string using a for statement (because it was used in the original code) including a div tag using a template literal.
Hello I've got a problem with fetch data in my javascript. I want to fetch api but everytime when I want to do this, somethink goes wrong. First I want to fetch html template, and this is working fine but when I want to use JS script from this file then it shows that 'function is not defined' I was trying many ways to do that. Below is code what doesn't work
var dataset;
fetch('../templates/mainPage.html')
.then(response => response.text())
.then(data => {
dataset = data;
document.getElementById('mainContent').innerHTML = dataset;
//var script = document.createElement('script');
//script.src = '../js/mainTmpl.js';
//document.body.appendChild(script);
//document.body.innerHTML += '<script defer src="../js/mainTmpl.js"></script>';
//script.addEventListener('load', logDataset);
logDataset();
});
and below is template what I want to use (HTML template and JS script is added to main HTML but that show me 'logDataset is not defined'
<div class="content">
<div class="main-container">
<span class="main-text" id="main-text">{{TEST}}</span>
<div class="blue-line"></div>
<span class="sub-text" id='sub-text'></span>
</div>
</div>
<script>
window.logDataset = function () {
var thathref = window.location.pathname;
document.getElementById('mainContent').innerHTML = dataset;
var mainText = document.getElementById('main-text');
var subtext = document.getElementById('sub-text');
console.log('test');
fetch('http://localhost:8080/'+thathref).then(
function(u){ return u.json(); }
).then(function(data){
var data1 = JSON.parse(JSON.stringify(data));
mainText.innerHTML = data1[0].text;
subtext.innerHTML = data1[1].text;
console.log(data1[0].text);
}
);
}
I've comment different methods that I tried to have working fine but it's still bad (I have to have JS script in other files)
Below screen of error Error
Error2
https://stackblitz.com/edit/js-1clyno?file=index.html
12345678901236789012345678901
I have been struggling with this so hopefully someone can help!
So I am looking to change the inner html of a paragraph to another html element containing a div and script when my frame receives a message from the page code. I have this working only for when the inner html is set to replace with a normal string
like this
document.getElementById('demo').innerHTML = "testing" ;
the correct replacement shows up here
<p id="demo">testing</p>
but when I try and pass in the other html to replace that section like this:
document.getElementById('demo').innerHTML =
'<div id="tlkio" data-channel="regerhtrh" data-theme="theme--night" style="width:100%;height:400px;"></div><script async src="https://tlk.io/embed.js" type="text/javascript"></script>';
it does not work. I don't think it is a quotation issue because I wrapped the outsides of it with single quotes. not sure what else to try. Below is the full html and I would appreciate any help!
<!doctype html>
<html>
<head>
<script type="text/javascript">
function init () {
// when a message is received from the page code
window.onmessage = (event) => {
if (event.data) {
console.log("HTML Code Element received a message!");
insertMessage(event.data);
}
}
}
// display received message
function insertMessage(msg) {
document.getElementById('demo').innerHTML =
'<div id="tlkio" data-channel="regerhtrh" data-theme="theme--night" style="width:100%;height:400px;"></div><script async src="https://tlk.io/embed.js" type="text/javascript"></script>'
;
}
</script>
</head>
<body onload="init();" style="background-color:lightgray;">
<h1>HTML Component Test</h1>
<p id="demo">
should put html here
</p>
</body>
</html>
The major issue is the </script> closing tag in your code. It closes YOUR block, not the block you are inserting.
You have to do so:
var myHtml = "<div id='tlkio' data-channel='regerhtrh' data-theme='theme--night' style='width: 100%; height:400px;'></div><script async src='https://tlk.io/embed.js' type='text/javascript'></scr"+"ipt>";
Second, script you insert with innerHTML wont run. Use document.createElement('script') instead
UPDATE
Here is the jsFiddle: https://jsfiddle.net/ArtyomShegeda/62fdybc0/21/
You may consider swapping the Quotes used:
function insertMessage(msg) {
var myHtml = "<div id='tlkio' data-channel='regerhtrh' data-theme='theme--night' style='width: 100%; height:400px;'></div><script async src='https://tlk.io/embed.js' type='text/javascript'></script>";
document.getElementById('demo').innerHTML = myHtml;
}
This may add it, yet may not render it. You might consider creating the elements and appending them.
function insertMessage(msg) {
var tlkio = document.createElement("div");
tlkio.style.width = "100%";
tlkio.style.width = "400px";
tlkio.setAttribute('data-channel', 'regerhtrh');
tlkio.setAttribute('data-theme', 'theme--night');
var tlkScript = document.createElement("script");
tlkScript.src = 'https://tlk.io/embed.js';
tlkScript.type = 'text/javascript';
tlkScript.async = true;
document.getElementById('demo').append(tlkio, tlkScript);
}
Based on some research here: load scripts asynchronously, it may be best to append the script to the <head>.
Hope that helps.
Update 1
Per your fiddle, once updated, it is working as you suggested: https://jsfiddle.net/Twisty/62fdybc0/7/
The following is added to #myDIV element:
<div style="width: 100%; height: 400px;" data-channel="regerhtrh" data-theme="theme--night"></div><script src="https://tlk.io/embed.js" type="text/javascript" async="async"></script>
I have the following code that I use to retrieve the hostname of a server and append some text (a filename) to it and display it on an html page.
<script type="text/javascript">
function getBaseUrl() {
var re = new RegExp(/^.*\//);
}
</script>
<script type="text/javascript">
document.write(getBaseUrl() + "filename.ext");
</script>
That generates a server URL such as https://fqdn/folder/filename.ext which is exactly what I need. Everything I have tried to create a link from it breaks things. How do I make that generated text clickable?
It's pretty straight forward to do -
const link = getBaseUrl()+ "filename.ext";
createLinkNode(link, document.body);
// defining a function to create a link node, however this isn't neccessary,
// you could just hard code the logic above.
// I wouldn't recommend setting innerHtml in lieu of making a text node however.
function createLinkNode(url, parent) {
const linkTextNode = document.createTextNode(url);
const linkNode = document.createElement('a');
linkNode.href = url;
linkNode.appendChild(linkTextNode);
parent.appendChild(linkNode);
}
example: https://jsfiddle.net/f4wxvLky/3/
You'd need to wrap it in an <a href=''></a>. This is easiest if you assign the <a> element in question to a variable, as you can then use .href to modify the link, along with .innerHTML to modify the text:
function getBaseUrl() {
return 'http://www.google.com/';
}
const output = document.getElementById('output');
output.innerHTML = 'Link Title';
output.href = getBaseUrl() + "filename.ext";
<a id="output" href=""></a>
If you don't have access to the HTML, this can still be done with raw JavaScript by simply including the <a href=''></a> wrapper in your output, being careful to also output the single quotes:
function getBaseUrl() {
return 'http://www.google.com/';
}
document.write("<a href='" + getBaseUrl() + "filename.ext" + "'>Link Title</a>");
Try this out, I assume getBaseUrl() is working although this doesn't look like. Just a reminder that <a> tag needs to be under the <script> block
<script>
function getBaseUrl() {
var re = new RegExp(/^.*\//);
}
</script>
Click
I want to convert the following string to HTML tags and place it inside my div.
<strong>asdfadfsafsd</strong>
I am using the following code to place it inside my div:
var message = "<strong>testmessage</strong>";
document.getElementById('message').innerHTML = bericht;
The problem is that I see the following in my div now:
<strong>testmessage</strong>
But I want to see:
testmessage
What is the problem?
var string = "<strong>asdfadfsafsd</strong>",
results = document.getElementById("results")
results.innerHTML = string;
results.innerHTML = results.textContent;
<div id="results"></div>
At first load the it as html. Then fetch it as text and then again load it as HTML :)
Refer HTML Entities
Try createElement
var tag = document.createElement("strong");
var t = document.createTextNode("testmessage");
tag.appendChild(t);
document.body.appendChild(tag);