Avoid html form classic behaviour with ajax [duplicate] - html

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.

Related

is nested function calling possible in jquery

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");
});
});

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.

Read the contents of a link or script tag using src/href

How can I read the contents of a file using
<link href='path/to/file'/>
I understand that if one adds the attribute type="text/css" then they can be read using document.styleSheets but I have a hard time figuring out how to get the content of that element though.
I understand that lesscss.js lib uses the without an ajax get call.
From: http://lesscss.org/#using-less
<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="less.js" type="text/javascript"></script>
I need to include some templates into the page, and the sooner they are loaded the better, ( vs doing it after jquery and js has loaded)
Thanks!
I understand what you mean with before jquery. But what do you mean with "before js".
When you load less.js (which does NOT depend on jQuery) the browser runs less.js before jquery has been initialized. Notice that less.js requires JavaScript.
You can read the content of such a file leveraging a XMLHttpRequest. A basis example which shows you how to do this can be found at: How to show the compiled css from a .less file in the browser?
Regarding less.js, you can find the source of that file at: https://github.com/less/less.js/blob/master/dist/less-1.7.4.js
I understand that if one adds the attribute type="text/css" then they can be read using document.styleSheets but I have a hard time figuring out how to get the content of that element though.
Globally less.js uses two steps to do that:
first it will built a list of paths as follows:
//
// Get all <link> tags with the 'rel' attribute set to "stylesheet/less"
//
var links = document.getElementsByTagName('link');
less.sheets = [];
for (var i = 0; i < links.length; i++) {
if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) &&
(links[i].type.match(typePattern)))) {
less.sheets.push(links[i]);
}
}
Then reads the content of these files by using a XMLHttpRequest too. See the doXHR function at line 7720 of less-1.7.4.js.

Using <script> in CSS

Is there any way to write script in css and call or execute it whenever required ?
I need a <script> tag to be executed .
i need something like this..
css code
#execute{
<script> ..some script.. </script>
}
so whenever i use
<html>
.
.
.
.<div id="execute" />
.
.
.
.
</html>
so if i change the script changes will be reflected everywhere.
Is it possible?
EDIT:
Is it possible to keep my <script></script> tags inside some js file and i will host it. and then i will call some function() from my HTML so that the script will be executed everywhere i need it.
Can someone show me any example, tutorial how i can do it.
I don't have much information about the Js file and how the function should be called.
Thank you all
Does it have to be in CSS? jQuery is a great, simple way to do what you're asking. You put all your style information in the CSS (what it's intended for) and keep your javascript in the html or a .js file. Take a look at http://jquery.com. The code would look something like this
$(function() {
$('#execute')
.someCoolFunction()
.anotherCoolFunction();
});
You use $(function() { /* code */ }); to run the code when your document is ready, and you use $('#execute') to grab the element with the execute tag. You can then do a lot of cool javascript really easily with that jQuery element.
No, you cannot mix CSS and Javascript this way. Why would you want to?
If you simply want a common JavaScript include, do it like this:
<script type="text/javascript" src="yourscript.js"></script>
You can't do this in standard CSS.
There is a way in which you can run code from within the CSS context, using a technology called 'Behaviours', referencing an HTC file (which is basically Javascript) in the stylesheet.
However, this technology is non-standard, and only exists in IE. It is therefore only really used to write hacks to make IE support features that it doesn't have which are in other browsers. An example of this in use is CSS3Pie.
If you're working on a site which will never be used in any browser other than IE, and you're happy to use a non-standard technology, then you may consider this to be the exact answer to your question. However I would strongly recommend you don't do this.
More realistically, you should be using a Javascript library such as JQuery, as the functionality you describe is pretty much standard fare for JQuery.
With JQuery, you would write code like this (in a normal script block, not in the CSS!):
$('.execute').each(function() {
/* your code here; it would be run for each element on the page with the class of 'execute' */
}
As you can see, it uses a CSS-style selector syntax to select the elements to work with.
(also NB: I've used execute as a classname here, not as an ID, because you imply that you want more than one of them -- note that you should never use the same ID more than once in any HTML page; it is invalid. If you need the same thing several times, use a class.
JQuery has functionality to watch for changes to elements, respond to events such as clicks or mouse over, and much more. Other similar libraries such as Prototype, MooTools and Dojo would also be able to do a similar job.
Hope that helps.
[EDIT]
Given the edit to your question, can you not just place the advertisment <script> tag inside the <div> on the page where you want it?
So with JQuery, you could write something like this to run your ad in each place you want it:
HTML:
....
<div class='execute'></div>
....
<div class='execute'></div>
....
Javascript code (remember to also include the JQuery library, or this won't work):
$(document).ready(function () {
$('.execute').each(function() {
advertisement(this); //change to whatever the advertisement script function is called.
});
});
Hopefully that will get you started. I can't really help you much more without knowing more about the advertisement script, though.
Also, the people who supplied the advert script should be able to tell you how to use it.
I believe a Javascript library like JQuery or Dojo is what you are looking for. It will allow you to add event handlers on tags with certain CSS attributes, which will behave exactly like what you are trying to do right now.
EDIT
Here is an example with Dojo pulled from the Google CDN that will popup an alert window when you click on any <div class="execute"></div> block:
<html>
<head>
<style>
<!--
.execute { background-color: red; height: 25px; }
-->
</style>
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6.0/dojo/dojo.xd.js" ></script> <!-- load Dojo from Google CDN
<!-- Let's register a onClick handle for any .execute div. -->
<script>
dojo.ready(function() // Dojo will run this after being initialized
{
// Get A list of all tags with id execute and add a event onClick
dojo.query(".execute").connect("onclick", function(evt)
{
alert("Event triggered!");
// ...
});
});
</script>
</head>
<body>
<div class="execute">Click me 1</div>
<br /><br />
<div class="execute">Click me 2</div>
</body>
</html>
Edit 2
This example uses an onClick event but Dojo (JQuery) allows you to do much more things. For instance if you wanted to dynamically add an image or something onLoad inside .execute divs, you could do it with Dojo (JQuery) in a similar way to this.
Doing it with a library saves you a lot of effort, but if you still want to write and call your own functions from javascript files, this is a rough idea of how you would do it:
// myScript.js
function foo()
{
// ...
}
// page.htm
<html>
<head>
<script src="path/to/myScript.js"></script>
</head>
<!-- ... -->
<div class="execute">
<script>
<!--
// Call foo()
foo();
-->
</script>
</div>
<!-- ... -->
It doesn't really make sense to abstract a script into CSS like that, and even if it was a good idea, it can't be done.
Why do you need to run the same script over and over in different places? Consider whether or not there might be a better or simpler way to do whatever it is you're doing.
Plus, when you include a script with the src attribute in the script tag, if you modify the script's source file, the changes persist everywhere.
No, but you can use script to alter the CSS properties of any element in the DOM.

How to call Processing.js function from HTML?

I'm exploring HTML5 and Processing.js.
When the user clicks on an image on my webpage, I'd like to call a function in the Processing.js code. Just calling the function in onclick, as illustrated in this simple example, isn't working:
<html>
<head>
<script language="javascript" src="processing.init.js"></script>
<script language="javascript" src="processing.js"></script>
</head>
<body>
<script type="application/processing">
void restart()
{ /* does something */ }
</script><canvas>
You'll need a browser that supports HTML5 to see this content.
</canvas><br/><br/>
<img src="restart-image.png" onclick="restart()">
</body>
</html>
Any thoughts on how I can call a method in the Processing.js script when an image is clicked? (Maybe I'm making a basic HTML mistake by using img onclick?)
This should work, enclose you image inside the anchor tag <a> image </a>
Use href tag to call the function.
image source
I would start by pulling the javascript for the onclick out of the img tag.
In a separate javascript file you can have:
document.getElementById('restartimage').onclick = function() { Processing.setup(); }
Obviously I put an id attribute on your img tag.
The setup function I noticed on this page:
http://processingjs.org/
The basic idea is that by pulling the onclick into a javascript file it will be easier to code what it should do.
you need to change the script-type to text/javascript or application/javascript first.
then place 'function' before 'restart()' function reducing 'void'.
i have used firefox 3.0.14 on ubuntu 9.04.
You can call processing functions using the Processing js object's getInstanceById function.
For example here is a function:
$(window).resize(function(){
var p=Processing.getInstanceById('processing_canvas_id');
p.resize($("#main").width(),$("#main").height());
});
Where resize is my processing function inside the processing file associated with processing_canvas_id.