is nested function calling possible in jquery - html

I'm using a script to call a separate file and inside that file I'm calling another file.
The script I'm using to call is this:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous">
</script>
<script>
$(function(){
$("#socials").load("sources/socials.html");
});
</script>
<script>
$(function(){
$("#icon").load("img/icon.xml");
});
</script>
and I'm calling the file like this:
<div id="socials"></div>
and inside socials.html, I'm calling the icon.xml like this:
<div class="email-bg">
</div>
it's not working for me when I try it like this. Is it not possible to do or is this just the incorrect way?
EDIT
I explained it in a comment below so I'll include the comment here too, I think it makes a little more sense what I'm trying to accomplish:
Essentially I have two standalone files that I am referencing, file A and file B. I am referencing file B inside of file A. When I reference file A in index.html, it works fine except that file B will not get referenced and I don't see the content of file B. BUT if I reference file A and file B directly in index.html without referencing, I can see the content of both files as expected

.load() is asynchronous, and the second function isn't waiting for the first one to finish, so the #icon element isn't in the DOM when it runs. You need to do it in the callback function.
$(function() {
$("#socials").load("sources/socials.html", function() {
$("#icon").load("img/icon.xml");
});
});

Related

Avoid html form classic behaviour with ajax [duplicate]

I noticed that the <script src="..."></script> tag does not allow you to use JavaScript within it, such as:
<script src="myFile.js">
alert( "This is a test" );
</script>
And this does not work, nor does it throw an error in FireBug, why is this happening, why do we have to add extra <script> tags to allow for JS to be used on the form itself?
Example
I have a file, found # script/addScript.js from my root, and this contains:
function addScript( $src )
{
var script = document.createElement( 'script' );
script.type = "text/javascript";
script.src = $src;
document.getElementsByTagName( 'head' )[0].appendChild( script );
}
This is designed to allow me to add scripts to the DOM quickly and effectively, so I tried to do this:
<script src="script/addScript.js">
addScript( "script/obj.js" );
addScript( "script/home/login.js" );
</script>
But it did not work, so I have to do this instead:
<script>
addScript( "script/obj.js" );
addScript( "script/home/login.js" );
</script>
A script element loads a single script.
It can do that from either a URL or from inline, but it still loads one script; it can't use both types of source at the same time.
If you try to include both, the inline script will be ignored:
<script src="example.js">
this_is_ignored();
</script>
… so you need multiple script elements.
<script src="example.js">
</script>
<script>
this_is_NOT_ignored();
</script>
It is worth noting that the content of the script element will still exist in the DOM, so some people use it to store data in it which the JS referenced by the src will read. data-* attributes are (arguably) a cleaner approach to that though.
Each <script> element contains one piece of executable javascript code. If you use a src attribute to load an external file, that is the piece of executable js for that element, otherwise it is the code placed between the <script></script> tags. If you try to do both, then you're attempting to associate two pieces of executable code to one script element and that is not the behavior of the script element so the browser's javascript engine ignores the inline code and executes the included file code.
As to why this is the case, it was likely a design choice by whoever established this standard. By creating a one-to-one relationship between code pieces and <javascript> elements there is no ambiguity about what code is being run or its priority.
Therefore in your case you will first have to load your external file...
<script src="script/addScript.js"></script>
and then call any functions provided by it.
<script>
addScript( "script/obj.js" );
addScript( "script/home/login.js" );
</script>
For reference, this is generally how all javascript libraries are loaded within a webpage.

Reference/Failed to load js Error: Vanilla Javascript not recognizing method and loading script

The following has occurred:
ReferenceError: anputAccept is not defined]
<script type="text/javascript" src="tshirt1.js"></script> <--this is failing to load.
I have created a .js file that has a method in it named anputAccept. This is located within Script tags in HTML at the bottom of the body tags.
document.getElementById("pushme").addEventListener("click",inputAccept);
The actual method is set like this in .js
function anputAccept() { //Statements here };
Can anyone explain exactly what is going on, and why the script fails to run? Why is there a Reference Error? This is caused because the script fails to load?
Put <script type="text/javascript" src="tshirt1.js"></script> to the bottom of the HTML page or you can you can try this:
window.onload = function() {
document.getElementById("pushme").addEventListener("click",inputAccept);
};

Update html file content

I worked on a little startpage for my browser. Now I would like to make some changes to it, so it updates the index.html file depending on a text file, when this got changed. What whould be an efficiant way to solve this problem?
My approach would be to create a text file and read line by line from it and update the html file. In the text file I would store the links shown on my startpage - I thought maybe something like this:
|cat_media
https://mailbox.org,mail
https://netflix.com,netflix
...
http://crunchyroll.com,crunchy
https://jott-uh-be.bandcamp.com,bc
|cat_social
https://pr0gramm.com,pr0
https://stackoverflow.com,stackoverflow
https://twitter.com,twitter
https://instagram.com,insta
When the line starts with the symbol |, it creates a new <div> with the class category and the string in that line (e.G. class= 'category cat_media'). Otherwise, if the line starts with http, it will add a href-link (e.G. <a href='https://mailbox.org'>mail</a>) to the html-code.
I got this website hosted on my raspberry pi with nginx and uploaded it to my github pages.
You don't have to update the index.html file.
You can create dynamic content.
You can use PHP:
You can learn it here:
https://www.w3schools.com/php/default.asp
And here is how to read a file
http://php.net/manual/en/function.fread.php
Or if you cant use PHP you can use Javascript:
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(() => {
$.ajax({
url:'your-config-file.xt',
success: function (data){
console.log(data); //this is the config file. just for loop it and modify the dom
}
});
});
</script>
But your config file must contains the string how the links should be shown.
For example:
|catergory one
yt: https://www.youtube.com

How to separate html text file into multiple files?

Very basic question about html.
Because the <body> is too long, I want to divide the file into multiple files. It is not about using iframe etc, but just want to include multiple text files to create <body> of the html file.
Thank you!
You can do it using jQuery:
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#ContentToInclude").load("b.txt or b.html");
});
</script>
</head>
And load it in HTML:
<body>
<div id="ContentToInclude"></div>
</body>
Just change the extension to .php instead of .html. Then you can just put, for example, your whole head inside the file head.php( or head.inc).
The whole thing would look something like this then:
<!DOCTYPE html>
<?php
include 'head.php';
?>
<body>
<!-- stuff in here -->
</body>
<html>
You can obviously split your body up into seperate pieces like this:
<body>
<?php
include 'firstPart.php';
?>
<!-- some other stuff -->
</body>
You can easily break your code in multiple files, Then create one file with .php extension and include them all!
With only HTML it would not be possible you need to add some JavaScript to be able to do so.
Using a data attribute with the Fetch API and some async functions you could do it as follow:
HTML file:
<div data-src="./PATH/filename.html"></div>
This element will receive as HTML content the content of the file specified in its data-src attribute.
Now the JavaScript:
async function getFileContentAsText(file) {
const response = await fetch(file);
const fileContent = await response.text();
return fileContent;
}
async function insertContentsFromFiles() {
const tbl = document.querySelectorAll('[data-src]'); // get elements with the data attribute "data-src"
for (var i=0; i < tbl.length; i++) // loop over the elements contained in tbl
tbl[i].innerHTML = await getFileContentAsText(tbl[i].dataset.src);
}
// dont forget to call the function to insert the files content into the elements
insertContentsFromFiles();
When the insertContentsFromFiles() method will be called it will first retrieve all the elements that have the data attribute data-src then we loop over these elements using their data-src value with the getFileContentAsText() method to affect their innerHTML property as the content of the file specified in the data attribute.
As we are using querySelectorAll() to get the elements with the data-src attribute the above JavaScript code will work for an unlimited amount of elements as long as they have that data attribute.
Note: In its current state the above JavaScript code is not optimized for loading a big amount of files as it process the files to be loaded one by one. If you are interested in solving this issue you may want to use promise.all() and update the insertContentsFromFiles() method to parallelize the files loading by taking advantage of the asynchronous operations.
Warning: If you plan to use elements that are in the loaded files from JavaScript you will have to retrieve them after they have been loaded into the page otherwise they will have an undefined value. To do so you can dispatch an event when a file has been loaded so you can attach specific functionnalities to the page based on the triggered events.

Use project Javascript and CSS files in a Google Apps Script web app?

If I create a simple HTML web app in Google Apps Script, like this:
function doGet() {
return HtmlService.createHtmlOutputFromFile("index.html");
}
and index.html looks like this:
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<div>Test</div>
is it possible to add JS and CSS files as part of the project and include them using script and link tags, or do they have to be inline/hosted elsewhere?
Here is a workaround I have found useful:
Add this function to your server-side Javascript:
function getContent(filename) {
return HtmlService.createTemplateFromFile(filename).getRawContent();
}
Add a second 'html' file to your project that contains only the JS or CSS surrounded by <script> or <style> tags as appropriate.
<!-- myscript.js.html -->
<script>
alert("Script included!");
</script>
Now you can include the script in your main HTML template like this:
<?!= getContent("myscript.js") ?>
This way, you can have your JS and CSS split into as many files as you like and keep them all accessible from within the Apps Script project.
Google provides a similar solution here.
Basically, they suggest you add this function to your .gs file:
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.getContent();
}
and add one or both of these to your .html file:
<?!= include('Stylesheet'); ?>
<?!= include('JavaScript'); ?>
the names in quotes of course referring to separate .html files containing your JS or CSS code with <script> or <style> tags.
You can't have simple js or css files in the project so what you do instead is create html files that contain it, and preferably you place the < script>< /script> or < style> inside those files.
So you might have a file a file named myscript.js.html with the following content:
<script>
alert ("Hello World!");
</script>
Now you put this line in the html where you want the asset to be included
Put this in the html where you want to include the asset:
<?= HtmlService.createHtmlOutputFromFile('myscript.js').getContent() ?>
Notice that the ".html" in the filename is omitted.
If you're going to include a number of assets it might be a good idea to make a helper-function. You can put the following function in your code (gs-file)
function include(filename) {
return HtmlService.createTemplateFromFile(filename).getRawContent();
}
Then the line above can be changed to:
<?!= include('myscript.js') ?>
Finally, you also need to call the evaluate()-method of the HTMLTemplate or else the code inside <?!= ?> in the html file wont be evaluated.
So if you're serving the html file like this for instance:
var html=HtmlService.createTemplateFromFile('repeatDialog');
SpreadsheetApp.getUi().showModalDialog(html, 'foo');
You simply need to change it to:
var html=HtmlService.createTemplateFromFile('repeatDialog').evaluate();
SpreadsheetApp.getUi().showModalDialog(html, 'foo');
If you were using createHtmlOutputFromFile and not createTemplateFromFile before then you should know that evaluate() returns htmlOutput so if you're wondering where to put things like .setWidth() then it's after the evaluate() call.
For now, it is not doable to have your CSS and JS script to be part of your Google Apps Script project. You will have to host it somewhere else and point the URL in your template.
You can directly render a file inside a scriptlet tag.
<?!= HtmlService.createTemplateFromFile("example.js").getRawContent() ?>
Create the example.js.html file in your apps script project. While rendering in the scriptlet tag do not mention the extension ".html"