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>
Related
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>
this is a very odd problem indeed and I hope it's simple. I cannot get a simple select and append to work in my html document, but it works when I'm in the chrome browser console.
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.3.min.js" integrity="sha256-aaODHAgvwQW1bFOGXMeX+pC4PZIPsvn2h1sArYOhgXQ=" crossorigin="anonymous"></script>
<script src="/js/script.js"></script>
<script>
$('[data-js="works"]').append("hello");
</script>
</head>
<body>
<div data-js="works"></div>
test
</body>
</html>
When I put that line of script in the console, hello appears above test. When I just open the page, test is there alone. I was running a script from this page earlier and when I tried to select an element it didn't work. I then went to inline script to see if it would even work there, no. I've seen if it works from inline script without the imported script, also no. Console has no bug information. I can print from that inline script to my console if I want, but this code still isn't running properly.
Doesn't work with my local httpserver and doesn't work just as a locally opened file.
This is because the script is executed before the page is loaded so the target div does not exist yet.
The solution is to wait for the page to be fully loaded before doing something.
The $ function can be used for this. Give it a callback and it will be executed once the page is loaded.
You can also use window.addEventListener("load", callback); that doesn't need jQuery.
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.3.min.js" integrity="sha256-aaODHAgvwQW1bFOGXMeX+pC4PZIPsvn2h1sArYOhgXQ=" crossorigin="anonymous"></script>
<script>
$(function(){
$('[data-js=works]').append("hello");
});
</script>
</head>
<body>
<div data-js="works"></div>
test
</body>
</html>
Another solution can be to insert your script at the end of the page. It is not as neat though in my opinion.
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.3.min.js" integrity="sha256-aaODHAgvwQW1bFOGXMeX+pC4PZIPsvn2h1sArYOhgXQ=" crossorigin="anonymous"></script>
</head>
<body>
<div data-js="works"></div>
test
<script>
$('[data-js=works]').append("hello");
</script>
</body>
</html>
Try the following, hope it will solve your problem
(function($) { // This will solve namespace problem (if any)
// Write your JQuery code here
})(jQuery);
Either you put the .js file at the end of the body or put your JS code between $(document).ready(function(){ //code inside })
Should I wait for DOMContentLoaded event if I place a script tag with the corresponding JS file at the end of a body tag?
index.html
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="popup.css">
</head>
<body>
<div id="container"></div>
<script src="popup.js"></script>
</body>
</html>
popup.js
document.addEventListener('DOMContentLoaded', onDOMContentLoaded);
Basically no. If script modifies element, it needs to exist.
If you put script after that element it exists.
If you put it Before, it does not exist and you may want to use DOMContentLoaded to wait for script to execute until it's sure it exists.
<div id="myid"></div>
<script>
getElementById('myid'); // it will work, Element myid Is defined
<script>
But this
<script>
getElementById('myid'); // it will fail, it's not yet defined, it will be
// Using DomContentLoaded here would be requrired
<script>
<div id="myid"></div>
<script></script> tag is for allowing client side scripting inside the code. When browser gets the HTML code , it first downloads all the script.
If they are not loaded dynamically like marked as defer or async, they'll load in sequential order.
The inline scripts are loaded after external scripts have been loaded first.
There is no perfect order when you load scripts in async mode.
My webpage has the following code:
<html>
<head>
<title>This is test Page</title>
<script language="javascript" type="text/javascript">
document.getElementById("msg1").innerHTML = document.URL.toString();
</script>
</head>
<body>
<div class="sss">
<p id="msg1"></p>
</div>
</body>
</html>
As you now at the time the script executes the div doesn't exist but I want to put my JavaScript code only In the <head> tag and I won't put it in middle of HTML code.
But this code only works when I put the <script> tag after the <div> tag.
I use VS2010 and firefox 19.0.1
Is there anyway to put code in <head> tag?
Your script relies on the DOM being ready, so you need to execute that function call only after the DOM is ready.
<script language="javascript" type="text/javascript">
window.onload = function() {
document.getElementById("msg1").innerHTML = document.URL.toString();
}
</script>
The various tags in your HTML page are loaded and processed in the order in which they appear on the page. Your <script> tag is executed immediately when it is parsed in the <head>. This is before the <body> and the elements inside the <body> are parsed. So, the script tries to reference an element that is not defined at the time it is executed.
Michael Geary is right, in order to execute your code, I'd use jQuery library (a de-facto standard in JS development) and utilize the DOM ready event. This will ensure the code in the handler will execute once DOM is fully loaded.
<script>
$(function(){
$('#msg1').html(document.URL.toString());
});
</script>
I recommend to to use addEventListener like this:
<script language="javascript" type="text/javascript">
document.addEventListener("DOMContentLoaded",() => {
document.getElementById("msg1").innerHTML = document.URL.toString();
});
</script>
Your script uses dom element and must run after the dom loaded.
Wrap your code in a function and call it after dom loaded
function myfunc(){
//code here
}
window.onload = myfunc();
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.