Why document.ready waits? - javascript

I know that Document.ready - DONt wait for images to download.
So why it does here ?
http://jsbin.com/ehuke4/27/edit#source
(after each test - change the v=xxx in the img SRC)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
alert('0');
});
</script>
</head>
<body >
<img src='http://musically.com/blog/wp-content/uploads/2011/04/Google-Logo.jpg?v=42333' />
</body>
</html>

I think, the problem comes out from JSBin.com
Because, when you try this example on JSFiddle.net, it works properly
http://jsfiddle.net/vqte9/

It has to do with the fact that you're using "alert()", I think, though I'm not 100% sure why. If you change your code like this:
<body>
<div id='x'></div>
<img ...>
</body>
<script>
$(function() { $('#x').text("hello there"); });
</script>
you'll see that the text is filled in before the image loads.
edit — I don't know why this would make a difference, but I notice quite different behavior when I set up the ready handler with:
$(function() { whatever; });
and:
$(document).ready(function() { whatever; });
Now that's not supposed to be the case; the two forms are supposed to do exactly the same thing, as far as I know. However, they don't seem to. Here is a jsbin example that sets up the ready handler with the first form, and here is one that uses the second one. They behave very differently for me. I'll have to check the jQuery source to figure out how that can be true.
Here is the jQuery documentation explaining the equivalence of $(handler) and $(document).ready(handler).

Related

How can I run JavaScript function in my HTML

I wrote a function in JS code, and I want to run it from HTML, but I don't see any reaction, when I run the site.
I will show you example of html code and js code.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="test.js">
<script src="test.js"></script>
</head>
<body onload="add()">
<p id="add2"></p>
</body>
</html>
Here starts JS code
function add(a,b,c,d) {
return a + b + c + d;
}
document.getElementById("add2").innerHTML = add(5,10,15,20);
I hope I wrote it clearly and someone will tell me, what did I do wrong?
Your JavaScript code is in the head, which is before the body and everything else, so the JavaScript runs before the p element has been created (html is run line by line). To fix this issue, you can try putting the JavaScript at the end of the document, for example after body.
When a browser loads an HTML page, it reads your HTML from top-to-bottom.
So ordering is important.
There are complexities of course. I'm not talking about deferred or asynchronous scripts here. But the top-to-bottom simplification helps us understand your problem.
Your script is inside test.js, so it will be loaded and run before [body] is ready.
But test.js has this line:
document.getElementById("add2").innerHTML = add(5,10,15,20);
This line is not inside a function, so the browser will try to run it immediately.
The call to add() will work because it has been declared in the file. But document.getElementById("add2") will not, because it is an instruction to access the following HTML in the [body]:
<p id="add2"></p>
But the [body] has not been "read" yet, so the JavaScript DOM API does not know about it.
However, you have partially solved the problem already using the onload attribute of the [body] tag. You've just used the wrong function with it.
That onload is an instruction to run a function after [body] has been completely read. So if you changed your document.getElementById line to be inside a function:
function runWhenBodyHasLoaded () {
document.getElementById("add2").innerHTML = add(5,10,15,20);
}
And told the [body] tag to run the function after everything has loaded:
<body onload="runWhenBodyHasLoaded()">
Then <p id="add2"></p> will be ready in time to access it with document.getElementById.
Or with jQuery:
https://jsfiddle.net/bdgu8s4h/1/
Also consider loading your JS at the end (of body)
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="test.css">
</head>
<body>
<p id="add2"></p>
<script type="text/javascript" src="test.js"></script>
</body>
</html>
JS (jQuery):
$(document).ready(function() {
function add(a,b,c,d) {
return a + b + c + d;
}
$('#add2').html(add(5,10,15,20));
});
Hope this also helped, cheers

Show & Hide an element after click

What i want to do is simple. When i click the image, i want some message to appear.
Afterwards, when i click it again i want it to disappear. I have problems iplementing it
due to my lack of jQuery knowledge. I would appreciate some help with the following code, as well as some other implementations. I know i can do something with class="hidden" and have jQuery add/remove it but oh well.
This is what i'm trying to work with.
<!DOCTYPE html>
<html>
<head>
<script>
function greet(){
a = document.getElementById('here');
if (a.trim().length==0){
a.innerHTML = 'message!';
}
else{
a.innerHTML = '';
}
</script>
</head>
<body>
<img src="http://www.clker.com/cliparts/K/9/M/I/M/8/on-button-small-th.png" alt="alt" onclick="greet()"/>
<p id='here'></p>
</body>
</html>
EDIT: seems like i should use a.value, but i must be doing something else wrong too.
If you are using jQuery it is very simple; just use this as your JavaScript (don't forget to link the jQuery main library - I like the Google CDN for that). Just use the toggle function:
function greet() {
$('#here').toggle();
}
Also it is better to register the onClick through jQuery rather than your html (for examplesee this SO question). So that would be like this for the whole page instead :
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$( document).ready(function() {
$("#greet").click(
function () {
$('#here').toggle();
}
);
$("#here").hide();
}
</script>
</head>
<body>
<img id="greet" src="http://www.clker.com/cliparts/K/9/M/I/M/8/on-button-small-th.png" alt="alt"/>
<p id='here'><!--MESSAGE SHOULD BE HERE--></p>
</body>
</html>
Working example in jsFiddle.

Javascript: Can't get element using getElementById [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 6 years ago.
Ok. I need fresh eyes because I'm still on this s***d problem for one hour!
Here is my simple HTML code (testssio.html) that include javascript script:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var ssio = document.getElementById('ssio');
ssio.html = "it finally works!";
</script>
</head>
<body>
<div id="ssio"></div>
</body>
</html>
But it doesn't work! Using the debugger, I get:
Uncaught TypeError: Cannot set property 'html' of null /testssio/:6
Does anyone get it? I know it's not the correct place to look for debugging help, but I'll be crazy if I don't get it! So please, any help?
Tahnks in advance.
The reason for this is that scripts in the head load before the page is rendered. This means your content is not yet rendered and therefore not a part of document.
If you want to see this work, try moving your script below the element renders, like this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="ssio"></div>
<script type="text/javascript">
var ssio = document.getElementById('ssio');
ssio.innerHTML = "it finally works!";
</script>
</body>
</html>
A more standardized way of doing this is with events. Many people use jQuery but it can be done with plain js. This would mean changing your script like this:
<script type="text/javascript">
function WinLoad() {
var ssio = document.getElementById('ssio');
ssio.innerHTML = "It finally works!";
}
window.onload = WinLoad;
</script>
This way you can still leave it in the <head>.
Also, using .html is from jQuery. It is generally used as .html(content). If you want to use the plain javascript version use .innerHTML = content.
I mention jQuery so much because it is a highly used API. This quote is from their site:
jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.
Your code is running too early before the DOM is loaded and thus document.getElementById() doesn't find the element in the document yet.
You can either move your script tag down to right before the </body> tag or you can wait for the DOM to load before running your code with either the window onload event or a DOMReady event.
There are two errors here. First, you need to put the SCRIPT tag after the element. Second, it's not .html, but .innerHTML. So here is the corrected code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="ssio"></div>
<script type="text/javascript">
var ssio = document.getElementById('ssio');
ssio.innerHTML = "it finally works!";
</script>
</body>
</html>
you can use something like this
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
document.onload= function(){
var ssio = document.getElementById('ssio');
ssio.html = "it finally works!";
}
</script>
</head>
<body>
<div id="ssio"></div>

Very Simple jQuery .load Example Not Working

I think this is a very simple question, but I can't seem to get it to work. I need to use JavaScript (specifically jQuery, apparently) to grab some content from a page, and pull it into another page. I've researched this quite a bit, but can't seem to get even a very simple example to work.
Here is the page I'm trying to get content from:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Test</title>
</head>
<body>
<p>This is the test html page.</p>
</body>
</html>
Here is the page I'm trying to use to pull the content:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>PullData</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</head>
<body>
<ol id="result"></ol>
<script type="text/javascript">
$('#result').load('test.html');
</script>
</body>
</html>
When I open the page it doesn't seem to do anything. I'm basically trying to follow the examples from jquery.com: http://api.jquery.com/load/
Both html pages are in the same folder somewhere on my C drive.
What am I missing?
Thanks in advance for your help!
What browser are you using?
Because of same-origin policy, some browsers won't permit AJAX requests to file:/// URLs, even if the original file was loaded that way. I know this is true of Chrome, but haven't tested others.
What does your .load() error handler say? Oh...
It seems to make logical sense.
Checking the API on load you may want to see if it actually loads, or if it encoutners an error
$("#result").load("/not-here.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#result").html(msg + xhr.status + " " + xhr.statusText);
}
});
API LINK: http://api.jquery.com/load/
sometimes the debugging information is a good first step to any solution.
You have your script tags at the end of your page, which means the enclosed JS will be invoked as soon as the browser reaches it, which may not be before the DOM is ready (which means the <ol> might not be set up to get the content of test.html). Try enclosing your load in a $(document).ready() callback as follows:
<script type="text/javascript">
$(document).ready(function() {
$('#result').load('test.html');
});
</script>
Also why are you inserting a full HTML page into an ordered list? You should try an HTML snippet (no head & body tags) into a content holder such as <div> or <span> where it will be semantically correct.
If none of these things work, attach a callback as follows:
$('#result').load('test.html', null, function(responseText, textStatus, xhr) {
alert(textStatus); // see what the response status is
});
Where is the closing script tag?
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</head>
Your code needs to be
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
You must first check if your HTML is ready.
$(document).ready(function() {
$('#result').load('test.html');
});
To ensure #result1 is loaded, you need a document.ready event handler:
<script type="text/javascript">
$(document).ready(function(){
$('#result').load('test.html');
});
</script>
Hope this helps. Cheers

Shoud these two JQuery functions produce the same behavior?

Assuming I have the following two JQuery functions -
The first, which works:
$("#myLink_931").click(function ()
{
$(".931").toggle();
});
and the second, which doesn't work:
$("#myLink_931").click(function ()
{
var class_name = $(this).attr("id").split('_')[1];
$("."+class_name).toggle();
});
I want to replace the first with the second, which is more generalizable, but can't find any obvious syntactical problem with the second which might be preventing it from working.
My guess is there's a problem with the syntax:
"."+class_name
Is this bad syntax?
They work the same.
Working Demo
This is what debuggers are for. Step through the code and make sure class_name is calculated as you expect. The debugger should let you view the result of "."+class_name as well.
I created a sample page and dropped your example code in and it worked as expected. Perhaps there is another issue on the page? Can you post a link to the actual site?
Here is the code I used:
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script src="scripts/script.js" type="text/javascript"></script>
</head>
<body>
<div id="myLink_931">Click Me</div>
<div class="931">HI</div>
</body>
</html>
and the script file:
(function($) {
$(document).ready(function() {
$("#myLink_931").click(function() {
var class_name = $(this).attr("id").split('_')[1];
$("." + class_name).toggle();
});
});
})(jQuery);
Class names and IDs aren't allowed to start with numbers - doesn't explain why one works and the other doesn't though. Give us a bit more info as above.
Is it possible you're not wrapping your 2nd example in the ready syntax [i.e. $(function(){ })] which would mean that the elements haven't been created in the DOM yet?

Categories

Resources