I wrote a small page with jQuery and an external .js file. But it won't load the jQuery part. Here my Code:
<!DOCTYPE html>
<head>
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/testScript.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<button id="testBtn">Oh my Goood...</button>
<div id="testDiv">testText</div>
</body>
</html>
And here is my external Script:
alert("no jQuery");
$("button#testBtn").click(function(){
alert("Works!");
});
As you can see, jQuery will load before all other scripts. The alert pops up fine. But if I click the button, nothing happens. If I put the script inside the html document directly, the button event works as expected.
I reviewed these questions: Link and Link. But still not working as expected.
Instead of using the $(document).ready() method, you could also just move your javascript references to the bottom of the page, right above the </body> tag. This is the recommended way to include javascript in webpages because loading javascript blocks the page rendering. In this case it also makes sure the elements are already rendered when the javascript is executed.
You'll need to add the click function inside document ready.
$(document).ready(function(){
$("button#testBtn").click(function(){
alert("Works!");
});
});
Your method fails because the code is being executed as the page is being loaded and the elements it refers to haven't been loaded yet. Using $(document).ready holds the function execution till the DOM elements are ready.
Related
I have tried finding an answer to this on my own, but only found instructions on how to use onload events. I seem to be missing the point.
I've been taught that if I want something to happen when the page loads, I should use window.onload like this:
<script>
window.onload = dosomething();
function dosomething()
{
window.alert('hello');
}
</script>
But now that I am thinking on my own I wonder what the point of doing that is. Because this also produces the same result:
<script>
dosomething();
function dosomething()
{
window.alert('hello');
}
</script>
Anything I put at the top inside <script> is going to execute anyway... so what's the point of window.onload?
If you're directly running your code with dosomething();, you're delaying your browser's rendering for the time it takes your JavaScript code to run.
You can try to insert your code to the <head> of your html document:
<!DOCTYPE html>
<html>
<head>
<script>
dosomething();
function dosomething()
{
window.alert('hello');
}
</script>
</head>
<body>
Does not render before the alert is dismissed!
</body>
</html>
You'll see that the page stays blank until you dismiss the alert. So every second the browser takes to run your JavaScript code is a second that your users have to wait for the site to be rendered.
Now if you change the code to be run on body's onload, the page gets rendered before the alert is shown:
<!doctype html>
<html>
<head>
<script>
function dosomething()
{
window.alert('hello');
}
</script>
</head>
<body onload="dosomething()">
This page gets rendered before the alert!
</body>
</html>
Consider these two blocks of code:
<head>
<script>
alert(document.getElementById('foo').value);
</script>
</head>
<body>
<input id="foo" value="hello">
</body>
<head>
<script>
window.onload = function() {
alert(document.getElementById('foo').value);
}
</script>
</head>
<body>
<input id="foo" value="hello">
</body>
In the first example, we'll get an error because the element you are referencing isn't found when the script runs - and so you are trying to get value of null.
In the second example, document.getElementById() will find the element with the id foo, because window.onload will get fired only when the complete DOM has been loaded and so the element is available.
window.onload will fire once the DOM has finished loading. In your example, the DOM is not required. However, the following code will fail if the DOM has not yet loaded:
function doSomething() {
alert(document.getElementById('test').innerText);
}
// Throws: TypeError: Cannot read property 'innerText' of null
Assuming your page contains an element with id test, it will alert its text.
waiting for the onload event assures you that all of your scripts and resources are loaded
Assume you are using jquery in your page and you invoked a function that uses it directly without onload , you can't guarantee that the jquery file has been loaded, which will lead to errors and possibly ruining your whole logic
The onload event is handy to make sure the page is fully loaded before you run a script. For your example above it doesn't make sense, but if your page is still loading an item on the bottom and you try to call it then nothing will run.
I recommend using jQuery and using the ready function. This way you will ensure your page is completely loaded.
$( document ).ready(function() {
// This will only run after the whole page is loaded.
});
If you don't want to load query, just put your javascript at the bottom of the page. It's best practice, and ensures the DOM is loaded in full.
For more info on the jquery ready function go here: https://api.jquery.com/ready/
Why is $(document).ready needed after the <script> tag?
What would happen if we don't use $(document).ready?
$(document).ready is javascript code, so it has to be written in <script> element and after jQuery is loaded.
If you don't write $(document).ready, your code will not wait for DOM to load completely and execute the javascript code immediately.
If you're using script in <head> that is using/manipulating some elements from DOM, you'll need ready, otherwise you'll get null/undefined.
If you're using script at the end of <body>, then you'll be safe as all the elements are loaded.
Quoting as it is from jQuery Docs
While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.
In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.
Example? Sure!
In Head no ready
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script>
alert($('#myname').val());
</script>
</head>
<body>
<input type="text" value="Tushar" id="myname" />
</body>
</html>
At the end of body
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="text" value="Tushar" id="myname" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script>
alert($('#myname').val());
</script>
</body>
</html>
In head with ready
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
alert($('#myname').val());
});
</script>
</head>
<body>
<input type="text" value="Tushar" id="myname" />
</body>
</html>
For the <script> at the end of <body>, you can omit ready.
Why is $(document).ready really need after <script> tag when we use javascript.
It isn't.
What else if we don't use $(document).ready
First, understand why people use ready: It's used to delay the code within the function you pass into it until jQuery calls that function, which jQuery does when it thinks the document is fully loaded.
JavaScript code within script tags runs immediately. If the script tag is above an element it refers to, the element won't exist when the script runs:
<script>
$("#foo").show();
</script>
<div id="foo" style="display: none">...</div>
That div will not be shown, because it doesn't exist when the code runs. So people use ready to delay their code.
There's a better way if you control where your script tags go: Just put your script tag at the end of the document, just before the closing </body> tag:
<div id="foo" style="display: none">...</div>
<!-- ... -->
<script>
$("#foo").show();
</script>
</body>
All of the elements defined above the script tag will exist when the code runs. No need for ready.
The ready event occurs when the DOM (document object model) has been loaded.
Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions.
//Use ready() to make a function available after the document is loaded:
$(document).ready(function(){
$("button").click(function(){
$("p").slideToggle();
});
});
Like in the example above.
The ready() method specifies what happens when a ready event occurs.
Direct quote from Learn jQuery
A page can't be manipulated safely until the document is "ready."
jQuery detects this state of readiness for you. Code included inside
$( document ).ready() will only run once the page Document Object
Model (DOM) is ready for JavaScript code to execute. Code included
inside $( window ).load(function() { ... }) will run once the entire
page (images or iframes), not just the DOM, is ready.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JQuery - multiple $(document).ready …?
I have my JS code that is using jQuery within the jQuery Document Ready IE:
$(function() {
});
I am running multiple jQuery scripts on the page and all are contained within one $(function() { }); is there any reason I should break the scripts into multiple ready handlers? IE:
$(function() {
// First Script
});
$(function() {
// Second Script
});
//etc.
or is it okay to have multplie scripts within one? IE:
$(function() {
// First Script
//Second Script
//etc.
});
I assume one is just fine but I want to ensure there are no reasons I should use multiple ones.
You could have multiple document.ready handlers in your script(s), jQuery will merge them into a single one before executing anyway. But it's really not necessary to have many document.ready handlers. One is enough. And if you put your scripts always at the end of your DOM, just before the closing </body> tag you don't need to use any document.ready handlers.
For example:
<html>
<head>
<title></title>
... your CSS references come here
</head>
<body>
... the markup of the body comes here ...
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
// you don't need to use any document.ready handlers here =>
// you could directly write your scripts inline or reference them
// as external resources. At this stage the DOM will be ready
</script>
</body>
</html>
It makes absolutely no difference with regards to how it works.
However, it can be useful for organision.
On the other hand, it means more jQuery has to run.
You can wrap all of your scripts/functions inside of a single ready event or you can simply place all of your scripts after your html and then avoid having to wait for a ready event because the DOM is already loaded by this point.
<html>
<head>
<!-- Style sheets Go Here -->
</head>
<body>
<!--HTML Goes Here -->
<!-- Scripts Go Here -->
</body>
</html>
I have been trying to use the document.getElementByID to pull information from an HTML file from an external JS file and it does not seem to be working. Does the document.getElementByID only work if it is inline with the HTML file or can it work properly on an external JS file? The JS file is called upon within the HTML document properly because other functions are working.
First off, make sure you're using document.getElementById("xxx"), not document.getElementByID("xxx") (note the difference in capitalization at the end). Your question refers to document.getElementByID("xxx") so that could be the problem right here.
Second, you must make sure that the function is executed AFTER the relevant DOM items have been parsed by the browser. If you are putting the document.getElementById in an external JS file that is loaded in the <head> section and is executed immediately after it loads, then the DOM will not yet be ready.
You have several options:
1) Place the external JS file <script> tags at the end of the body, right before the </body> tag. This will not only load/display your page faster, but will guarentee that the DOM is parsed before anything in that JS file can run.
<body>
Your HTML here
<script type="text/javascript" src="myscript.js"></script>
</body>
2) Since you have jQuery, put your immediately executed code inside of a $(document).ready(fn) block so that jQuery will hold back the execution until the DOM is ready. If you do it this way, then you can put your code anywhere (including in the <head> section if you want).
$(document).ready(function() {
// put your page initialization code here
});
3) Put your code anywhere you want, but don't have any of it execute immediately. Instead, put all your initialization code in an intialization function (let's call it myPageInit() that you call from:
$(document).ready(myPageInit);
4) Put your code anywhere you want, but don't have any of it execute immediately. Instead, put all your initialization code in an intialization function (let's call it myPageInit() that you call from a script right before the </body> tag with this:
<script type="text/javascript">myPageInit()</script>
Does the document.getElementByID only work if it is inline with the HTML file
No.
can it work properly on an external JS file?
Yes.
You're probably calling document.getElementById() before the DOM is ready.
My suggestion is to do this:
window.onload = function () {
// document.getElementById() code here
}
Then your document.getElementById() would not execute until every element on the page has fully loaded.
If you put the script in the <head> then the body hasn't loaded yet and so the elements aren't there.
Either defer the script by using jQuery's functions, or put the script at the end of the body.
window.onload = function() {
document.getElementById("demo").innerHTML = "My First JavaScript";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>js in ts</title>
<script src="app.js"></script>
</head>
<body>
<h2>JavaScript in Body</h2>
<p id="demo"></p>
</body>
</html>
I have a simple single page setup. Under a root folder, I have 3 subfolders (js, css, and images). In the root folder, I have an index.html page with the following content:
<html>
<head>
<title></title>
<script language="javascript" src="js/jquery-1.3.2.min.js"></script>
<script language="javascript" src="js/myscript.js"></script>
</head>
<body>
<a onclick="doSomething()" href="#" class="doSomething">Click!</a>
</body>
<html>
myscript.js contains the following code:
$('a.doSomething').click(function(){
//Do Something here!
alert('You did sometihng, woo hoo!');
});
When I click the link, nothing happens. What am I missing?
Wrap document.ready around the code:
$(document).ready(function() {
$('a.doSomething').click(function(){
//Do Something here!
alert('You did sometihng, woo hoo!');
return false; // return false to prevent default action
});
});
As it is right now, you are trying to bind an event to an element that does not yet exist in the DOM.
Also, not sure why you have the onclick on the link itself, as the whole point of jQuery is to be able to take those ugly inline events out of there and bind them cleanly in the javascript. If you do this:
yay click me
And then use the code above, it should work fine.
At first I thought you were just missing a function named "doSomething". Then I realized you where expecting your selector to find the anchor tag anyway. However, that won't happen. At the time your script runs, the anchor hasn't been added to the DOM yet.