Execute JavaScript code at the end when the HTML has been loaded - javascript

I want to execute a function at the end when the HTML has been loaded. I tried it with onload without success. I also tried it with ready, but it still doesn’t work. Here is my code. This is again placed in the header:
<script type="text/javascript">
$(document).ready(function() {
$('#infowindow_content').html('test');
});
</script>
The div is also set by an external JavaScript file. Content:
window.onload = initialize;
function initialize() {
document.getElementById('infowindow_content').innerHTML = 'testa';
}
It is included the following way before the closing body tag:
<script type="text/javascript" src="../lib/functions.js"></script>
I tried to place the above code before the closing body tag, but currently I have no idea why this doesn't work (the content isn't changed by my JavaScript code). If I execute it on the console afterwards everything works fine.
Solution:
I set a configuration parameter (language) in the HTML file. In the JavaScript file I ask for this value and depending on the value I define another content. Sometimes it could be so simple ...

Try this:
setTimeout(function() {
$(document).ready(function() {
$('#infowindow_content').html('test');
});
}, 20);

I don't know the jQuery equivalent but try the native JS.
Since the <body> has the most HTML & loads after <head>...
document.body.onload=function(){
yourFunction(args)
}
<body onload="yourFunction(args)">...</body>
Or maybe the window object, since it's the root of every webpage DOM...
window.onload=function(){
yourFunction(args)
}

Always place DOM manipulating code directly before your </body> tag. JavaScript in the header should only be called to libraries, such as jQuery.

Related

Alternative to hide/show content with JS?

is there a better way to replace this kind of js function by simply collapse/toggle a div and show/hide its content?
$(function() {
$('#destselect').change(function(){
$('.dest').hide();
$('#' + $(this).val()).show();
});
});
The reason this is happening is because your js file is called on the head of your page.
Because of this, when you document.getElementsByClassName('collapsible');, colls result in an empty array, as your elements in body are not yet created.
You could either create a separate js file and add it at the end of your body (in that way you make sure your colls are created when your javascript is executed), or just wrap your code on a DOMContentLoaded event listener that will trigger your code once the document has completely loaded.
My guess would be that you are loading your script before browser finishes loading dom conetent and so when it runs the elements it is trying to add event listeners to, don't yet exist.
Try wrapping all you javascript in that file in this:
document.addEventListener("DOMContentLoaded", function(event) {
// all your code goes here
});
The above makes sure that your script is run after loading all elements on the page.
You could add a script tag to the header of your HTML file, this will import the JS file into your current page as follows
<script src="File1.js" type="text/javascript"></script>
Then call the function either in onclick in a button or in another script (usually at the bottom) of your page. Something like this:
<body>
...
<script type="text/javascript">
functionFromFile1()
</script>
</body>
Seems like your script is not executing properly due to a missing variable.
In this script https://www.argentina-fly.com/js/scripts.js
Naves variable in function UpdateDetailsDestination() is not defined.
I think you should resolve this first and then check your further code is working on not.
Please take a look into Console when running page. You'll see all JavaScript related errors there.

Function is not found in Jquery, but is found in Javascript

I have an html document in which a function is called like this
<div id="mon" class="topbar" onclick="verd()">
This calls a jquery function inside the body tag that goes like this
<script src="jquery.js">
function verd(){
$("#stillmain").empty();
} </script>
This returns the error:
Uncaught ReferenceError: verd is not defined
at HTMLDivElement.onclick
When I change the script to pure Javascript without Jquery however like this
<script>
function verd(){
$("#stillmain").empty();
} </script>
it does recognize the function verd(), can anyone explain what is going on, and how I could still use Jquery?
I am using the newest version of Jquery(just changed the name, nothing else).
When you give a script tag a src attribute it's going to load that source file in place of the script contents. So any script tags with a src should be kept empty.
You need to load jQuery by calling a script tag with its source on it, and then in a separate tag you can make your own script tag and write your custom JavaScript there.
<script src="jquery.js"></script>
<script>
function verd(){
$("#stillmain").empty();
}
</script>
Make sure that your custom scripts are loaded after jQuery.
If you want to run this as a jQuery function you need to use the proper syntax. Try the link below.
How to Create a jQuery Function
Also, you need to load jQuery in a separate tag or else none of your code will be ran other than the source of that script!

JavaScript in the head tag

I have a html file which looks like this.
<head>
<script>
document.onready
{
document.getElementById("demo").innerHTML="Works";
}
</script>
</head>
<body>
<div id="demo">
</div>
</body>
When I put the script tags at the bottom of the page, everything works fine. But when I put the script in <head></head tag, it does not work. I guess it is not able to access elements that are below the script.
On many sites like StackOverflow, JavaScript is in head tag. How is it then able to access HTML elements that are below it?
What should I do now? Should I just move my script to the bottom or is there a way by which JavaScript can access elements below it?
Try using something like this:
window.addEventListener('load', function() { document.getElementById("demo").innerHTML="Works"; }, false);
Where did you get document.onready from? That would never work.
To ensure the page is loaded, you could use window.onload;
window.onload = function () {
document.getElementById("demo").innerHTML="Works";
}
Your syntax is incorrect.
document.ready= function () {
//code to run when page loaded
}
window.onload = function () {
//code to run when page AND images loaded
}

executing javascript function from HTML without event

I wish to call a javascript function from an HTML page and I do not want it dependent on any event. The function is in a separate .js file since I wish to use it from many web pages. I am also passing variables to it. I've tried this:
HTML:
<script type="text/javascript" src="fp_footer2.js">
footerFunction(1_basic_web_page_with_links, 1bwpwl.html);
</script>
The function in fp_footer2.js:
function footerFunction(path, file) {
document.write("<a href=" + path + "/" + file + " target='_blank'>Link to the original web page for this assignment.</a>");
return;
}
(I have also tried putting the fp_footer2.js file reference in the header, to no avail. I'm not sure if I can put it 'inline' like I did in this example. If not, please let me know.
PS: I know I can do this with a simple 'a href=""' in the HTML itself. I wanted to see if this could work, for my own curiosity.
If a <script> has a src, then the external script replaces the inline script.
You need to use two script elements.
The strings you pass to the function also need to be actual strings and not undefined variables (or properties of undefined variables). String literals must be quoted.
<script src="fp_footer2.js"></script>
<script>
footerFunction("1_basic_web_page_with_links", "1bwpwl.html");
</script>
JavaScript will run while your page is being rendered. A common mistake is to execute a script that tries to access an element further down the page. This fails because the element isn't there when the script runs.
So includes in the <head> will run before any DOM content is available.
If your scripts are dependent on the existence of DOM elements (like a footer!) try to put the script includes after the DOM element. A better solution is to use the document ready event ($(document).ready() in jQuery). Or window.onload.
The difference between documen ready and window onload is that document ready will fire when the DOM has been rendered; so all initial DOM elements will be available. Where as window onload fires after all resources have loaded, like images. window onload is useful if you're doing things with those images. Usually document ready is the right one.
Maybe I misunderstand your question, but you should be able to do something like this:
<script type="text/javascript" src="fp_footer2.js"></script>
<script type="text/javascript">
footerFunction(1_basic_web_page_with_links, 1bwpwl.html);
</script>
Have you tried calling it from a document.ready?
<script type="text/javascript">
$(document).ready(function() {
footerFunction(1_basic_web_page_with_links, 1bwpwl.html);
});
</script>

Javascript on loaded page not executed

// Change the value of the outputText field
function setAjaxOutput(){
if(httpObject.readyState == 4){
document.getElementById('maincontent').innerHTML = httpObject.responseText;
}
}
i try to load a page which contain this script
<script type="text/javascript">
$(document).ready(function() {
alert('dfd');
$("#formAddUser").validate({
rules: {
userImage: {
required: true,
accept: "png|jpg|gif|jpeg"
}
}
});
});
</script>
<div class="content-box">
<div class="content-box-header">
........................
Why javascript on loaded page not executed? Thank you.
Your problem is that innerHTML doesn't execute scripts in the HTML fragment. When you say 'element.innerHTML = htmlfragment;', it just adds the tags and renders the HTML. Script tags are not rendered as part of the HTML by the browser, so they are ignored.
You need to use jQuery.load() instead of jQuery.ajax() like this:
$('#maincontent').load('yourscript.php');
jQuery.load(); has code inside that first takes those tags out, then adds the remaining HTML via innerHTML, then runs the tags separately. You can see the code that does this here at around line 211. From the docs:
When calling .load() using a URL without a suffixed selector
expression, the content is passed to .html() prior to scripts being
removed. This executes the script blocks before they are discarded. If
.load() is called with a selector expression appended to the URL,
however, the scripts are stripped out prior to the DOM being updated,
and thus are not executed.
first try:
<script type="text/javascript">
alert('dfd');
</script>
and then try
<script type="text/javascript">
$(document).ready(function() {
alert('dfd');
});
</script>
and paste the results.
I believe your form comes with ajax. so it is better if you can turn your validation into a function, and call it inside ajax loaded content.

Categories

Resources