I'm trying to get my JavaScript to work when I insert the script into the head or body elements.
Here are my examples:
Firstly I insert it into the body like this example (working):
<html>
<body>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color = "blue";
</script>
<p>The paragraph above was changed by a script.</p>
</body>
</html>
When I move the script into the end of the body (also working):
<html>
<body>
<p id="p2">Hello World!</p>
<p>The paragraph above was changed by a script.</p>
<script>
document.getElementById("p2").style.color = "blue";
</script>
</body>
</html>
But when I move it into the head it stops working:
<html>
<head>
<script>
document.getElementById("p2").style.color = "blue";
</script>
</head>
<body>
<p id="p2">Hello World!</p>
<p>The paragraph above was changed by a script.</p>
</body>
</html>
Use keyword defer for this:
Description of defer:
A script that will not run until after the page has loaded.
<html>
<body>
<p id="p2">Hello World!</p>
<script defer>
document.getElementById("p2").style.color = "blue";
</script>
<p>The paragraph above was changed by a script.</p>
</body>
</html>
you can use window.onload which means that it will invoke only after HTML page is loaded. Here is a quick reference for your study . Thank You!
the problem is your script in head and p2 has not define yet
so you write script in document.ready its work because script run after document has been load
for run jquery code you need to add jquery library for this
link:jquery library
or write code in
window.onload = function() {
document.getElementById("p2").style.color = "blue";
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script>
$(document).ready(function() {
document.getElementById("p2").style.color = "blue";
});
</script>
</head>
<body>
<p id="p2">Hello World!</p>
<p>The paragraph above was changed by a script.</p>
</body>
</html>
it is because you are calling p2 at head and it is not defined at that moment. compiler don't know where is p2 that's why it is showing undefined.
One of the solutions is to do it like below:
window.onload = function () {
document.getElementById("p2").style.color = "blue";
}
The above script will run when the page is loaded completely
"Why it does not work when I insert script in head?"
This is because the script is trying to access a DOM object before it exists. It's one of the main reasons jQuery users tend to use $(document).ready(); wrapped around there functions.
An older practice was to always load your script below the body of your HTML document, however it came with it's own problems.
Using <script defer> /* your code here */ </script> is the generally accepted method if you want your script to only execute after the document is loaded. Alternatively, you can use an external library like jQuery and use:
$(document).ready(function(){
//your code here
});
If you do decide to use jQuery, you could also replace your current script (document.getElementById("p2").style.color = "blue";) with:
$(document).ready(function(){
$('#p2').css({'color':'blue'});
});
This however isn't necessary, just an interesting option to consider
When your script code is in the head tag, it is executed but the DOM element is not ready yet. So, no change occurs. For such cases always use body.onload, because then your script will be executed after the elements in the body is ready.
Bonus: The script will also not work if you place it in the <body> above the <p> tag.
Related
from the html below I would like to execute a script by calling his id. So that when the script id is called the display fonction execute. Any other suggestion will be appreciate as long that the script only execute when the id is called. Thank you
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
//Here is where I would like to execute the script by calling his id.
//Any other suggestion to make it work will be appreciate
});
</script>
<script type="text/javascript" id="execute">
$(document).ready(function(){
display();
});
</script>
<!--------------------- Footer -------------------------------->
<script>
function display(){
$("#show").css("display", "block");
}
</script>
<p id="show" style="display:none">This is a paragraph with little content.</p>
</body>
</html>
That's not how JavaScript works.
Once you include a <script> in DOM, it's executed. However, the script itself can define functions, which could be named and called at a later point (by their name), by any other script or element in the page, as long as they have access to the context in which you defined your function.
Example:
<script>
function myFunction() {
window.alert('I got called!');
}
</script>
<button onclick="myFunction()">Execute myFunction()</button>
So instead of using the id of the script, I'm using the name of the function.
To fully answer your question: running a script by id is not possible because all scripts are executed as soon as they are parsed by the browser (which happens in their chronological order in DOM) and there is no way of re-running them after they have already been executed.
Obviously, one could argue that you could remove the <script> tag altogether, create a new one with the same contents, which is going to be rerun when added to DOM. But, at least in theory, it's not rerunning the same <script>, it's running a different one. Another instance/<script> tag.
Needless to say, nobody does that as it's much more convoluted than to simply define a function and call that function at a later time.
Thank you for your explanation on the DOM. It help me figure out another alternative
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
var result = window.prompt("Would you like the footer to be display?");
if(result == "yes"){
bodyPage1();
}
});
</script>
<script>
function bodyPage1(){
display();
}
</script>
<!--------------------- Footer -------------------------------->
<script>
function display(){
$("#show").css("display", "block");
}
</script>
<p id="show" style="display:none">This is a paragraph with little content.</p>
</body>
</html>
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 simply trying to create some simple vector graphics using the Javascript Library Raphael. There should be a square object and a curved object, but nothing is being displayed. Can anyone help me. Thank you.
<html>
<head>
<script src="raphael.js"></script>
<script src="jquery-1.7.2.js"></script>
<script type="text/javascript"> //all your javascript goes here
var paper = Raphael("sample-2", 200, 100);
var rectPath = paper.path("M10,10L10,90L90,90L90,10Z");
var curvePath = paper.path("M110,10s55,25 40,80Z");
rectPath.attr({fill:"green"});
curvePath.attr({fill:"blue"});
</script>
</head>
<body>
<div id="sample-2" style="width:500px; height:500px;">
</div>
</body>
</html>
Move your script to after the <div id="sample-2" style="width:500px; height:500px;"> tag
Or some people prefer to use the onload handler, using jQuery for simplicity
$(function(){
// Your code that runs after the DOM is loaded
});
The key is that your code is accessing the DOM and it needs to run after the DOM has been built. Calling it from the onload handler or after the DIV you're using makes sure the element is ready to be interacted with.
You are running your Javascript far too early. Your browser will run Javascript as it reads it and if the DOM elements have not been loaded, it will not do anything.
Try this:
<html>
<head>
<script src="raphael.js"></script>
<script src="jquery-1.7.2.js"></script>
</head>
<body>
<div id="sample-2" style="width:500px; height:500px;"></div>
<script type="text/javascript">
//all your javascript goes here
var paper = Raphael("sample-2", 200, 100);
var rectPath = paper.path("M10,10L10,90L90,90L90,10Z");
var curvePath = paper.path("M110,10s55,25 40,80Z");
rectPath.attr({
fill: "green"
});
curvePath.attr({
fill: "blue"
});
</script>
</body>
</html>
Enjoy and good luck!
#JuanMendes it is slightly confusing, in the end the problem is that the js functions are called before the DOM is ready, elemets are still being created. I recommend using $(document).ready(function(){}) so that the scripts are executed only after the DOM has been created. I'm just explaining again because he is asking why he has to do that. For example if he did:
<html>
<head>
<script src="raphael.js"></script>
<script src="jquery-1.7.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){ //all your javascript goes here
var paper = Raphael("sample-2", 200, 100);
var rectPath = paper.path("M10,10L10,90L90,90L90,10Z");
var curvePath = paper.path("M110,10s55,25 40,80Z");
rectPath.attr({fill:"green"});
curvePath.attr({fill:"blue"});
}
)
</script>
</head>
<body>
<div id="sample-2" style="width:500px; height:500px;">
</div>
</body>
</html>
That script should work because the script is executed after the DOM is ready.
P.S. On a side note if you want to manipulate content that is dynamically created on the fly, you need to attach the event handlers as click, blur, hover, etc... with a binding operation so the event is registered. Example:
$('#form').on('blur', '#input', function(){
// code
})
you can check out the Docs for binding at:
http://api.jquery.com/on/
and of .ready() at:
http://api.jquery.com/ready/
I really cannot understand why this does not work. I've tried couple of tricks but I just don't get it.
<html>
<head>
<script type="text/javascript">
alert('Hey');
var vText = document.getElementById("results");
vText.innerHTML = 'Changed';
alert(vText.innerHTML);
</script>
</head>
<body>
<div id="results">
hey there
</div>
</body>
</html>
This is working as you can see here:
http://jsfiddle.net/gHbss/
It's important that you put the JavaScript after your HTML div container.
The problem that you're facing is that the browser runs the JavaScript as it's encountered when rendering/processing the page. At this point it will alert() your message, but the relevant element, the #results div isn't present in the DOM, so nothing can be changed.
To address this, you can either place the script at the end of the page, just before the closing </body> tag, or run the code in the onload event of the body or window.
The script has to be placed after the div#results or executed onload, otherwise the element is still unknown when you try to access it.
You need to call this script in onload event
i.e
window.onload=function(){
//your code
}
<html>
<head>
<script type="text/javascript">
function onloadCall()
{
alert('Hey');
var vText = document.getElementById("results");
vText.innerHTML = 'Changed';
alert(vText.innerHTML);
}
</script>
</head>
<body onload="onloadCall()">
<div id="results">
hey there
</div>
</body>
</html>
Hope the above snippet shows you the fix
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.