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

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

Related

JavaScript button onclick not working

<button onclick="hello()">Hello</button>
<script>
function hello() {
alert('Hello');
}
</script>
This is my code. But it's not working. When I click on the button nothing happens.
Note to other developers coming across this, you can run into this if you use a reserved method names e.g. clear.
<!DOCTYPE html>
<html>
<body>
<button onclick="clear()">Clear</button>
<button onclick="clear2()">Clear2</button>
<script>
function clear() {
alert('clear');
}
function clear2() {
alert('clear2');
}
</script>
</body>
</html>
How about this?
<button id="hellobutton">Hello</button>
<script>
function hello() {
alert('Hello');
}
document.getElementById("hellobutton").addEventListener("click", hello);
</script>
P.S. You should place hello() above of the button.
Ran into this problem myself so I can confirm something's not right. The difference is that I am generating the DOm Element at runtime. Replacing onclick with onmousedown seemed to do the trick if you can't find a place to addEventListener in your code.
I had a similar issue. I had child.js and a common.js files. In my case, My HTML file was using both the JS files and both of them had a function with the same name,
child.js
function hello(){}
and also
common.js
function hello(){}
After I remove one of these my code works fine and onclick started working. hope this helps!
using onclick vs EventListeners.
The question is a matter of browser compatibility and necessity. Do you need to attach more than one event to an element? Will you in the future? Odds are, you will. attachEvent and addEventListener are necessary. If not, an inline event may seem like they'd do the trick, but you're much better served preparing for a future that, though it may seem unlikely, is predictable at least. There is a chance you'll have to move to JS-based event listeners, so you may as well just start there. Don't use inline events.
jQuery and other javascript frameworks encapsulate the different browser implementations of DOM level 2 events in generic models so you can write cross-browser compliant code without having to worry about IE's history as a rebel. Same code with jQuery, all cross-browser and ready to rock:
$(element).on('click', function () { /* do stuff */ });
Don't run out and get a framework just for this one thing, though. You can easily roll your own little utility to take care of the older browsers:
function addEvent(element, evnt, funct){
if (element.attachEvent)
return element.attachEvent('on'+evnt, funct);
else
return element.addEventListener(evnt, funct, false);
}
// example
~```
addEvent(
document.getElementById('myElement'),
'click',
function () { alert('hi!'); }
);
Try it: http://jsfiddle.net/bmArj/
Taking all of that into consideration, unless the script you're looking at took the browser differences into account some other way (in code not shown in your question), the part using addEventListener would not work in IE versions less than 9.
There is no problem with your code.. run this snippet
function hello() {
alert('Hello');
}
<button onclick="hello();">Hello</button>
and if you want to alert this on window load. change your code like this way
(function(){
alert('hello')
})();
Add:
type="button"
to the button element. The default type is "submit" which is submitting the form before the script is run.
In my case there are was two same elements with position: absolute. I set onclick on the first one so it haven't been called because second element was covering it
I had the same issue, for me, it did not work because of my main.js having type="module", if you don't need type="module" this will work.
<body>
<button onclick="onBtSave()">Save filter model script type module</button>
<button onclick="onBtRestore()">Restore filter model no script type</button>
<script type="module">
// broken
function onBtSave() {
console.log("saving current filter model");
}
</script>
<script >
// working
function onBtRestore() {
console.log("restoring current filter model");
}
</script>
This happened to me when I opened another folder in visual studio code. I just opened new window of visual studio code and only opened one folder this time and it now works
I had the same problem and that's because of reserved method names. We just change the function name.
function click() {
alert('hi')
}
function click1234() {
alert('hi')
}
<body>
<button onclick="click()">login</button>
<button onclick="click1234()">login1234</button>
</body>
For other devs with more advanced code, sometimes an absolute position element is blocking the button. Make sure no element is blocking the button(s) from being clicked.
Write a semicolon after hello function like this
<button onclick="hello();">Hello</button>

Javascript - calling/initialising a function from within a function

I've had a quick look but cannot find a specific answer for this query so thought I'd ask the experts. I'm still learning HTML and Javascript.
I have some code where I'm using the standard "body onLoad" function to run an "initialise" function located in the HTML doco head section. I have another function called "populateList(){...}" in the head which basically populates an array with data from an external file.
I want to initialise this list by calling the "populateList" function from within the "initialize" function. I've tried using populateList(); and other permutations but this doesn't seem to work. I assume this is a syntax query and should be straightforward so haven't included any code but will if it makes this clearer. Does the "populateList" function need to be specified before the calling function or does it iterate through functions before loading.
Thanks
Like this?
<html>
<head>
<script>
function initialise()
{
alert('initialise');
populateList();
}
function populateList()
{
alert('populate list');
}
</script>
</head>
<body onload="initialise()">
</body>
</html>
Demo: http://plnkr.co/edit/5HgzbiIHDXUijdSGSTzO?p=preview
If thats the case, Javascript works by loading scripts from top to bottom - so you will need to declare them in order.

Alert After jQuery Function is Finished

I'm trying very hard to figure out how to get a JS alert to appear only after a previous script (a glossary word replacement script) has finished. Getting this javascript/jquery to run in order is giving me a headache as it either runs out of order, or the second part doesn't run at all.
Here is the code that is presently working WITHOUT the alert:
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="jquery.zglossary.min.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
$('body').glossary('listofwords.json');
//want alert('finished') to happen after glossary word replacement is finished replacing words here
});
</script>
</head>
I've tried a lot of different things trying to get an alert to happen where that comment is, and either the alert happens immediately before any words are replaced by the zglossary script, an example of that would be:
<script>
$(document).ready(function () {
$('body').glossary('listofwords.json');
alert('finished');
});
</script>
Or the script will replace all the words and no alert happens at all. An example of that would be:
<script>
$(document).ready(function () {
$('body').glossary('listofwords.json');
}, function() {
alert('finished');
});
</script>
Another example of that happening (words are replaced, but no alert happens) that I've tried would be:
<script>
$(document).ready(function () {
$('body').glossary('listofwords.json', function() {alert('finished');} );
});
</script>
I really just can't figure this out. I'd appreciate any help
I've never used this glossary plugin before - but I downloaded the source and I see the issue is clearly because the glossary plugin does not provide any callback after the JSON data is asynchronously downloaded. Any solution that is not hacky will require a slight modification to the library itself.
Here is a quick way you could do it
By adding this line
typeof options.callback == 'function' && options.callback();
At the end of the success: function(data) {
Then your code would simply be this:
<script>
$(document).ready(function () {
$('body').glossary('listofwords.json', {callback:function() {alert('finished');}} );
});
</script>
Which is similar to your last example, only it puts the callback into an options JSON which is what the plugin expects.
I have no idea what's "Glossary", but you might find a solution with Deferred object supplied by jQuery api. Deferred helps to handle json calls, especially the .done() method to set a caalback when the call is finished.

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.

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

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/

Categories

Resources