JavaScript code place in the header - javascript

I am not clear why its not working the javascript code when I add it to the header section as follows.
We can place a javascript code within the body as follows
<html>
<head>
<title> Simple Test </title>
</head>
<body>
<div id="mydiv"> This is the div content </div>
<script type="text/javascript" >
document.getElementById("mydiv").innerHTML=Date();
</script>
</body>
</html>
But when I place the same JavaScript code in the header section it doesn't work.
<html>
<head>
<title> Simple Test </title>
<script type="text/javascript" >
document.getElementById("mydiv").innerHTML=Date();
</script>
</head>
Can Someone please explain the issue. I know I can Write a JavaScript function in header and call it in an event. But can't we Use in this way. If Can't why.

<html>
<head>
<title> Simple Test </title>
<script type="text/javascript" >
window.onload= function (){document.getElementById("mydiv").innerHTML=Date();}
</script>
</head>
I think above code will help you to solve your problem. You can try this one.

because when the page is loaded, by the time the browser gets to that <script> element, the #mydiv element has not yet been created.
either use an "onload" event, or put your scripts at the bottom of the page.

It's because the page is being rendered in the order it's read. Therefore when the script in the header is evaluated the rest of the page hasn't been rendered yet (ie the myDiv element hasn't been created).
When you create an event handler in the head that works fine - the handler is set up before the rest of the page is loaded but the event can't happen until the element exists.

When you put it in the <head>, it runs before the <body> exists.

this is because of the page rendering order.you can access elements before it has been created. if you can, try to put all JavaScript code end of the page(before closing body tag). it will save your page load time. if you cannot put it in the bottom, put the code inside onload event.

Related

Implement JS in HTML

It should be easy,
but as easy as it should be I can't solve the problem.
If I'm typing the following HTML and JS code into an online editor,
everything works fine but if I'm typing this into my (offline) editor it won't work.
Here's the online code:
http://jsbin.com/kenurunahu/1/edit?html,js,output)
I bet it has something to do with the loading order and how the files are linked.
Thats how my (lokal) HTML-file looks like (where the files are linked):
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" content="Index.css">
<script src="Script.js"></script>
</head>
<body>
<p id="demo">
something
</p>
</body>
</html>
Many Thanks for Help!
[Update]
Firefox and Chrome display the JS file. Sometimes I get an error message that says 'innerHTML is null', but if I write the same code into the console everything works fine.
you have the error when the js script is loaded before the html dom is fully loaded by the browser. A simple solution for your testing is to place the script include at the end of your html page, like this :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" content="Index.css">
</head>
<body>
<p id="demo">
something
</p>
<script src="Script.js"></script>
</body>
</html>
A better solution is to run your script only when the dom is fully loaded. For example with the body onload event :
<body onload="yourFunc()">
Or event better by using only js code, for example with jquery ready function or by writing a simple custom handler that should work on all major browsers :
document.addEventListener("DOMContentLoaded", function(event) {
//call your func here
});
Hope that helps.
A few guesses:
Capitalization is important. If the file is named script.js do not link to Script.js
Is your js file in the same folder as the index.html document? Because that is what you are saying.
Normally, we arrange our file structure something like this:
public_html
- css
- js
- img
- inc
If your styles/scripts are stored in sub-folders, such as js and css, then you must amend your references to:
<link rel="stylesheet" content="css/Index.css">
<script src="js/Script.js"></script>
As a good practice, your scripts should be placed at the closing of body tag. External scripts are blocking and hence it would make sense we do not put them at the top. Also, when your script placed at the top runs, your DOM may not be ready, which means any element your script is trying to access may not be present in DOM at all which results in your error.
Hence, all your scripts should be at the closing of body tag. That way when the script loads and runs, you can be assured that the DOM is ready.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" content="Index.css">
</head>
<body>
<p id="demo">
something
</p>
<script src="Script.js"></script>
</body>
</html>

Calling javascript script from html

I have a simple javascript file like so:
$(document).ready(function () {
alert("my controller");
});
I have an HTML file like so:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript" src="/js/generateLineupController.js"></script>
</body>
</html>
for the love of all things holy why in the world would the alert not show? I get a 200 on GET for the javascript file, so it's loading.
Several problems here.
You're trying to load the script twice for some reason. Don't do that. Load it in <head>, or at the end of <body>, but not both.
You're trying to use jQuery syntax ($(...)), but you haven't loaded the jQuery library. You'll need that.
The $(document).ready(...) indicates that you are trying to use jQuery, but you aren't loading jQuery in your page. Check your console log; you will see the errors there.
Also, there's no need to load the script twice with two <script> tags; just load it once.

JavaScript not working as an external file

I'm new to HTML, JavaScipt and everything related to programming, and I'm trying to create a simple page.
Now, I'm stuck with the following problem: I want to change the date of my main.html file, but the main.js is not working. I've already change the <script> position to inside the <body>, after the </span> and even after the </body>, without success. If the content of the main.js is within the HTML it works fine, but as a external file it doesn't.
Here is my main.html:
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="main.js"></script>
<title>Page 1</title>
</head>
<body>
<p>WRF<br>
<span id="data">18/09/1987</span></p>
</body>
</html>
My main.js is just:
document.getElementById("data").innerHTML = "JUBA";
I've looked through the internet and through this forum, but all answers that I've found did not worked.
The files are on the same directory and the main.css works fine.
Thank you in advance.
At time you call main.js element #data was not created in DOM tree. You can fix this by putting the link to your Javascript file right before closing the body like this:
<script type="text/javascript" src="main.js"></script>
</body>
Document Object Model (DOM) is not "READY".
Try use onload event, inside main.js:
window.onload = function() {
document.getElementById("data").innerHTML = "JUBA";
};
If needs more "fast" than onload, use jquery with $(document).ready:
html:
<link href="main.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="main.js"></script>
main.js:
$(document).ready(function() {
$("#data").html("JUBA");
});
window.onload vs $(document).ready()
Answer by #Guffa:
The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.
The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.
The element is not yet accessible when you run the script.
Either you can put the script at the end of the page or delay the execution.
You could put the JavaScript in the <body> tag after the rest of the page. When the browser loads it, the <span> will already be there to be edited.
As per your code the script will be called first then page will be loaded, therefore when the script is running there will not be any element having id data because yet page have to be loaded. There are many ways to achieve what you need.
1. Add a script tag before or after end of body like
or
<script type="text/javascript" src="main.js"></script>
</body>
Write .js file above before body i.e. in head tag and write the whole javascript code in onload method.
window.onload=function(){
document.getElementById("data").innerHTML = "JUBA";
};
window.onload=function(){
document.getElementById("data").innerHTML = "JUBA";
};
<p>WRF<br>
<span id="data">18/09/1987</span></p>

javascript tag trigger - code position on page

i use that tag to alert me when a tag has been shows up
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
<iframe></iframe>
</body>
</html>
strange , since this code working :
<html>
<head>
</head>
<body>
<iframe></iframe>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
</body>
</html>
why the Js need to under the tag to work?
what's the problem here?
Because the code in a script tag is executed immediately. And in the first example the iframe doesn't exist at that time. But what you can do is to wrap you code into an onload (for the main page) event. E.g.:
window.onload = function() {
//your code
}
Then it doesn't matter where the code is placed.
Iframe tag does not exist at the moment you are trying to access it.
You may check that by simply alerting array length, like
alert(document.getElementsByTagName('iframe'));
Have you thought about executing your javascript after the page is loaded? You may use some frameworks like jQuery to facilitate crossbrowser issues. Or just put all your javascript code to the very bottom of body.

Basic jQuery .load Problem

I am trying to use jQuery's .load function to dynamically load content into my webpage. This seem so simple, but I cannot make it work. To try and figure it out, I made a test page with just basic structure, but the external content still won't load:
jquery.html
<html>
<head>
<title>JQuery Test</title>
<script src="jquery1.5.min.js"></script>
</head>
<body>
<script>
$('#foo').load('test.html');
</script>
<div id="foo"></div>
</body>
</html>
test.html
<p>Text text</p>
I'm sure I have made a tiny error, but I can't find it anywhere!
You need to encapsulate your script in the $(document).ready() otherwise #foo won't exist when the script is executed:
<script>
$(document).ready(function(){
$('#foo').load('test.html');
});
</script>
You need to wait for the document to be ready before you can access the DOM. Just add a $(document).ready() around your original code:
<html>
<head>
<title>JQuery Test</title>
<script src="jquery1.5.min.js"></script>
</head>
<body>
<script>
$(document).ready( function() {
$('#foo').load('test.html');
});
</script>
<div id="foo"></div>
</body>
</html>
or if you want a shorter code:
$(function() {
$('#foo').load('test.html');
});
Informally, what's happening is that, as your browser reads the code you wrote, it's drawing its contents as it goes along. When it reaches your <script> tag, it executes it. But when $("#foo") gets executed, the browser's still processing the <script> and hasn't reached the part of the code where you told it there's a div called foo, so the browser doesn't know it exists, and jquery will just find nothing.
Of course, the idea that the browser will just sequentially read your code and render it as it goes is naive at best, so while it might seem that just moving the <script> tag to the bottom of the code would work, you're not actually guaranteed it will work. Instead, the browser will notify you when it's done drawing the page by firing a load (and possibly a DOMContentLoaded) event. So all code that depends on the whole html being drawn should be executed in an event handler bound to those events.
jQuery makes waiting for the page to be loaded easy, just use something like this:
$.ready(function() {
doStuff();
});

Categories