jQuery - multiple $(document).ready ...? - javascript

Question:
If I link in two JavaScript files, both with $(document).ready functions, what happens? Does one overwrite the other? Or do both $(document).ready get called?
For example,
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript" src="http://.../jquery1.js"></script>
<script type="text/javascript" src="http://.../jquery2.js"></script>
jquery1.js :
$(document).ready(function(){
$("#page-title").html("Document-ready was called!");
});
jquery2.js:
$(document).ready(function(){
$("#page-subtitle").html("Document-ready was called!");
});
I'm sure it is best practice to simply combine both calls into a single $(document).ready but it's not quite possible in my situation.

All will get executed and On first Called first run basis!!
<div id="target"></div>
<script>
$(document).ready(function(){
jQuery('#target').append('target edit 1<br>');
});
$(document).ready(function(){
jQuery('#target').append('target edit 2<br>');
});
$(document).ready(function(){
jQuery('#target').append('target edit 3<br>');
});
</script>
Demo As you can see they do not replace each other
Also one thing i would like to mention
in place of this
$(document).ready(function(){});
you can use this shortcut
jQuery(function(){
//dom ready codes
});

It is important to note that each jQuery() call must actually return. If an exception is thrown in one, subsequent (unrelated) calls will never be executed.
This applies regardless of syntax. You can use jQuery(), jQuery(function() {}), $(document).ready(), whatever you like, the behavior is the same. If an early one fails, subsequent blocks will never be run.
This was a problem for me when using 3rd-party libraries. One library was throwing an exception, and subsequent libraries never initialized anything.

$(document).ready(); is the same as any other function. it fires once the document is ready - ie loaded. the question is about what happens when multiple $(document).ready()'s are fired not when you fire the same function within multiple $(document).ready()'s
//this
<div id="target"></div>
$(document).ready(function(){
jQuery('#target').append('target edit 1<br>');
});
$(document).ready(function(){
jQuery('#target').append('target edit 2<br>');
});
$(document).ready(function(){
jQuery('#target').append('target edit 3<br>');
});
//is the same as
<div id="target"></div>
$(document).ready(function(){
jQuery('#target').append('target edit 1<br>');
jQuery('#target').append('target edit 2<br>');
jQuery('#target').append('target edit 3<br>');
});
both will behave exactly the same. the only difference is that although the former will achieve the same results. the latter will run a fraction of a second faster and requires less typing. :)
in conclusion where ever possible only use 1 $(document).ready();
//old answer
They will both get called in order. Best practice would be to combine them.
but dont worry if its not possible. the page will not explode.

Execution is top-down. First come, first served.
If execution sequence is important, combine them.

Both will get called, first come first served. Take a look here.
$(document).ready(function(){
$("#page-title").html("Document-ready was called!");
});
$(document).ready(function(){
$("#page-title").html("Document-ready 2 was called!");
});
Output:
Document-ready 2 was called!

Not to necro a thread, but under the latest version of jQuery the suggested syntax is:
$( handler )
Using an anonymous function, this would look like
$(function() { ... insert code here ... });
See this link:
https://api.jquery.com/ready/

Related

Javascript document.ready in multiple files with Gulp [duplicate]

If I have a lot of functions on startup do they all have to be under one single:
$(document).ready(function() {
or can I have multiple such statements?
You can have multiple ones, but it's not always the neatest thing to do. Try not to overuse them, as it will seriously affect readability. Other than that , it's perfectly legal. See the below:
http://www.learningjquery.com/2006/09/multiple-document-ready
Try this out:
$(document).ready(function() {
alert('Hello Tom!');
});
$(document).ready(function() {
alert('Hello Jeff!');
});
$(document).ready(function() {
alert('Hello Dexter!');
});
You'll find that it's equivalent to this, note the order of execution:
$(document).ready(function() {
alert('Hello Tom!');
alert('Hello Jeff!');
alert('Hello Dexter!');
});
It's also worth noting that a function defined within one $(document).ready block cannot be called from another $(document).ready block, I just ran this test:
$(document).ready(function() {
alert('hello1');
function saySomething() {
alert('something');
}
saySomething();
});
$(document).ready(function() {
alert('hello2');
saySomething();
});
output was:
hello1
something
hello2
You can use multiple. But you can also use multiple functions inside one document.ready as well:
$(document).ready(function() {
// Jquery
$('.hide').hide();
$('.test').each(function() {
$(this).fadeIn();
});
// Reqular JS
function test(word) {
alert(word);
}
test('hello!');
});
Yes you can easily have multiple blocks. Just be careful with dependencies between them as the evaluation order might not be what you expect.
Yes it is possible to have multiple $(document).ready() calls. However, I don't think you can know in which way they will be executed. (source)
Yes it is possible but you can better use a div #mydiv and use both
$(document).ready(function(){});
//and
$("#mydiv").ready(function(){});
I think the better way to go is to put switch to named functions (Check this overflow for more on that subject).
That way you can call them from a single event.
Like so:
function firstFunction() {
console.log("first");
}
function secondFunction() {
console.log("second");
}
function thirdFunction() {
console.log("third");
}
That way you can load them in a single ready function.
jQuery(document).on('ready', function(){
firstFunction();
secondFunction();
thirdFunction();
});
This will output the following to your console.log:
first
second
third
This way you can reuse the functions for other events.
jQuery(window).on('resize',function(){
secondFunction();
});
Check this fiddle for working version
Yes you can.
Multiple document ready sections are particularly useful if you have other modules haging off the same page that use it. With the old window.onload=func declaration, every time you specified a function to be called, it replaced the old.
Now all functions specified are queued/stacked (can someone confirm?) regardless of which document ready section they are specified in.
Yes, it's perfectly ok.but avoid doing it without a reason. For example I used it to declare global site rules seperately than indivual pages when my javascript files were generated dynamically but if you just keep doing it over and over it will make it hard to read.
Also you can not access some methods from another
jQuery(function(){}); call
so that's another reason you don't wanna do that.
With the old window.onload though you will replace the old one every time you specified a function.
It's legal, but sometimes it cause undesired behaviour. As an Example I used the MagicSuggest library and added two MagicSuggest inputs in a page of my project and used seperate document ready functions for each initializations of inputs. The very first Input initialization worked, but not the second one and also not giving any error, Second Input didn't show up. So, I always recommend to use one Document Ready Function.
You can even nest document ready functions inside included html files. Here's an example using jquery:
File: test_main.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="jquery-1.10.2.min.js"></script>
</head>
<body>
<div id="main-container">
<h1>test_main.html</h1>
</div>
<script>
$(document).ready( function()
{
console.log( 'test_main.html READY' );
$("#main-container").load("test_embed.html");
} );
</script>
</body>
</html>
File: test_embed.html
<h1>test_embed.html</h1>
<script>
$(document).ready( function()
{
console.log( 'test_embed.html READY' );
} );
</script>
Console output:
test_main.html READY test_main.html:15
test_embed.html READY (program):4
Browser shows:
test_embed.html
You can also do it the following way:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("#test").hide();
});
$("#show").click(function(){
$("#test").show();
});
});
</script>
</head>
<body>
<h2>This is a test of jQuery!</h2>
<p id="test">This is a hidden paragraph.</p>
<button id="hide">Click me to hide</button>
<button id="show">Click me to show</button>
</body>
the previous answers showed using multiple named functions inside a single .ready block, or a single unnamed function in the .ready block, with another named function outside the .ready block. I found this question while researching if there was a way to have multiple unnamed functions inside the .ready block - I could not get the syntax correct. I finally figured it out, and hoped that by posting my test code I would help others looking for the answer to the same question I had

toggle two images on click

I'm trying to use someone's code from an earlier post that I posted on here, and in it, he provided a jsFiddle that shows how to toggle between two images.
I'm trying to replicate exactly what that person is doing, but it doesn't seem to work on my code:
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script>
$('#ellomatey').toggle(
function(){
$(this).attr('src', 'bgimage.png');
},
function(){
$(this).attr('src', 'redsquare.png');
});​
</script>
</head>
<body>
<img id="ellomatey" src="bgimage.png" />
</body>
</html>
Does anyone know what I'm doing wrong? I have a feeling that it's not calling the function correctly, but it seems to work on that person's example.
The other two answers talk about the actual problem, but they don't tell you how you get to discover that, this is where debugging comes into play.
console.log("before");
$('#ellomatey').toggle(
function(){
console.log("bgimage"); $(this).attr('src', 'bgimage.png');
},
function(){
console.log("redsquare"); $(this).attr('src', 'redsquare.png');
});​
console.log("after");
If you do this, you'll notice "before" and "after" in your console. That's okay. But when clicking on the image, you would expect the other console logs, which means that the toggle function isn't doing what you thought it would do.
You can somewhat suppose the heavily used function to work properly, so there must be something up with the selector. Let's inspect that.
console.log($('#ellomatey'));
Heh, what?! No elements.
And then you start to think why and then you'll discover you need to wait till the DOM loaded; supposing you would have some underlying background in how a webpage loads, which is a prerequisite for what you're doing.
Wrapping
$(document).ready(function() { ... });
around it does exactly that.
All it takes is a little understanding and some simple debug output...
Don't just mindlessly code supposing it'll work, but verify your assumptions while you do it.
You need to wrap your code in a document.ready call. The way you have it the code will try to run before the actual content of the page has loaded.
<script>
$(document).ready(function() {
$('#ellomatey').toggle(
function(){
$(this).attr('src', 'bgimage.png');
},
function(){
$(this).attr('src', 'redsquare.png');
});​
});
</script>
You're defining your toggle function for an element that doesn't exist yet in the document, so you should wrap the js code on window.load handler (assuming you want to wait the complete image load) or at document.ready event
I created a flexible toggle script:
jsBin demo
put the second image url inside an data attribute for your image:
<img id="ellomatey" src="img_1.jpg" data-src="img_2.jpg" />
and on click just call the 'swap' function!
$(function(){ // BTW, you were just missing this 'ready' function :)
function swap(){
var mem = this.src;
this.src = $(this).data('src');
$(this).data('src',mem);
}
$('#ellomatey').click( swap );
});
This snippet can also handle multiple elements by just nesting your elements:
$('#ellomatey, .button, #something').click( swap );
(Added also in the demo a pure JS version. Have fun!)

JQuery selector - #ElementId not working just ElementId is fine

I am having some issues showing a div that i am hiding. For some reason the #ElementId selector isnt working but if i just use ElementId it works.
Jquery 1.7.1 also I am using JQuery ui.
$('CreateGroup').show("fold"); // this works fine
$('#CreateGroup').show("fold"); // this fails with cannot call show on undefined
<div id="CreateGroup" style="display: none">Hi!</div>
What's going on?
Thanks
Are you sure the element is already created when you call the function?
try this to ensure it to run after the DOM is ready:
$(window).ready(function() {
$('#CreateGroup').show("fold");
});
More info:
.ready()
Both should fail.
Your code is not possible since you are not using the document.loadevent (aka $(function(){}); aka $('document').ready().
The node have not yet been defined when the script is called.
This would work however:
<div id="CreateGroup" style="display: none">Hi!</div>
<script type="text/javascript">$('#CreateGroup').show("fold");</script>
Since it's invoked AFTER the node definition.
You don't how to worry about that if you use the mentioned load methods.
<script type="text/javascript">
$(function() {
$('#CreateGroup').show("fold");
});
</script>
<div id="CreateGroup" style="display: none">Hi!</div>
That will work since the script is not executed until the whole document have been loaded.
#Piercy, chances are your $() function comes from Prototype, not jQuery. Are you including both libraries in your page? – Frédéric Hamidi Mar 2 at 12:21
This was correct it was prototype interfering. If I use the fully jQuery qualifier it works.

A good cross-browser "ready" event without using jQuery?

I need to create the equivalent of jQuery's ready event without using jQuery. It needs to work on as many browsers as possible and cannot mess up the body.onload handler (i.e. if there's already a handler set, the function shouldn't overwrite it). I checked jQuery's code but don't understand how it works because it uses many jQuery's functions.
Any suggestion on how to do that?
Edit: I have no control over where my code is going to be inserted that's why it needs to play as nicely as possible with the existing body.onload handler. It also means I cannot be sure the code will be inserted at the bottom of the page (most likely it won't be).
Smallest cross browser DOMReady code, ever.
<html>
<head>
<script>
var ready = function (f) {
(/in/.test(document.readyState)) ?
setTimeout('r(' + f + ')', 9) :
f();
};
</script>
</head>
<body>
<script>
ready(function () {
alert('DOM Ready!');
});
</script>
</body>
</html>
This may help:
http://www.freelancephp.net/en/domready-javascript-object-cross-browser/
Non jquery implementation of DOM ready
Simply include your <script> tag at the very bottom. This way, it will only load after all the rest of the content had finished loading.

AS3 navigateToURL(); javascript function not firing when using jQuery

I have a problem I cannot seem to solve. I am using AS3's navigateToURL(); function to call a simple javascript function. At the moment it just alerts the first parameter. The problem is, when this function is placed inside of the $(document).ready(function(){..}) block it does not fire. Example of my code:
<script type="text/javascript">
$(document).ready(function(){
function mapLink(aVar){
alert(aVar);
};
});
</script>
Example of simple AS3 call to function:
navigateToURL(new URLRequest('Javascript: mapLink("'+mapObject.tooltipMoreLink+'");'), '_self');
When the function is placed OUTSIDE of the jquery code, it works fine. Why does it need to be inside of the jquery code you may be asking? I need the jQuery DOM selectors to manipulate certain dom elements based on the value of 'aVar' in my javascript function.
Any guidance is welcomed with an open mind.
eh. this is what the ExternalInterface class was designed for.
You issue has to do with scope. Your function is scoped to the jquery object, and not globally, so it is invisible to your call. If you need jquery selectors, then you could easily set the flash var independently, followed by the jquery routine.
update
maybe I'm missing something, but shouldn't this be as be easy as:
function externalCall(param){
$(domElement).doSomething(param);
}
?
I wouldn't think this need be tied to the jq ready function. I mean, if flash has already loaded, and the user is interacting, then certainly the ready event has long since fired successfully.
Hope that helps. I'm not sure I'm following exactly what you're trying to do ;)
...
btw - I really would look into ExternalInterface, NavToURL may work, but you can call your js directly with the former method.
It won't work because you have created a function inside the DOMReady Event
that is $(document).ready and calling it from outside the scope of the function.
You can access jQuery DOM Selectors from anywhere provided you have referenced jQuery.js in your page.
Example
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<script type="text/javascript">
function mapLink(aVar){
alert(aVar);
}
</script>

Categories

Resources