i am trying to understand the following jquery code:
(function( window, undefined ) {
//All the JQuery code here
...
})(window);
If there is a .js file that is included in a page with the <script> </script> tag when will it fire and start runing the function?
It will run the function as soon as the contents of the <script> block are parsed.
Note that your code is different in an important way from:
$(function(jQuery) {
// code
});
The above arranges for the code to run when the document is ready (the DOM is fully parsed and built).
Related
is there a better way to replace this kind of js function by simply collapse/toggle a div and show/hide its content?
$(function() {
$('#destselect').change(function(){
$('.dest').hide();
$('#' + $(this).val()).show();
});
});
The reason this is happening is because your js file is called on the head of your page.
Because of this, when you document.getElementsByClassName('collapsible');, colls result in an empty array, as your elements in body are not yet created.
You could either create a separate js file and add it at the end of your body (in that way you make sure your colls are created when your javascript is executed), or just wrap your code on a DOMContentLoaded event listener that will trigger your code once the document has completely loaded.
My guess would be that you are loading your script before browser finishes loading dom conetent and so when it runs the elements it is trying to add event listeners to, don't yet exist.
Try wrapping all you javascript in that file in this:
document.addEventListener("DOMContentLoaded", function(event) {
// all your code goes here
});
The above makes sure that your script is run after loading all elements on the page.
You could add a script tag to the header of your HTML file, this will import the JS file into your current page as follows
<script src="File1.js" type="text/javascript"></script>
Then call the function either in onclick in a button or in another script (usually at the bottom) of your page. Something like this:
<body>
...
<script type="text/javascript">
functionFromFile1()
</script>
</body>
Seems like your script is not executing properly due to a missing variable.
In this script https://www.argentina-fly.com/js/scripts.js
Naves variable in function UpdateDetailsDestination() is not defined.
I think you should resolve this first and then check your further code is working on not.
Please take a look into Console when running page. You'll see all JavaScript related errors there.
This might be a stupid beginner's problem, but it's driving me mad. Simplified, the code is:
I have an index.php where in an inline script (located in the head element), some JS functions are defined.
<script type="text/javascript">
$(function(){
// other code
var popup = function(message,color){
$(".title").css({"color": "beige" });
$(".popup_alert").css({"background-color": color});
$( ".popup_alert" ).append(message);
$(".popup_alert").removeClass("offscreen").delay(800).queue(function(){
$(this).addClass("offscreen").dequeue();
$(this).empty();
$(".title").css({"color": "#444" });
});
};
};
</script>
At the very bottom of the <body>, I'm loading an external JS file where some JQuery happens:
<script src="ajaxToDB.js" type="text/javascript"></script>
JQuery is not the problem. It's loaded and the other functions inside this external file are working.
Inside this linked file, I can't call the function defined in the index.php.
popup("test",orange);
Will yield a console error "Uncaught ReferenceError: popup is not defined"
Is this normal? I already wrapped all the stuff in ajaxToDB.js inside a
$(function() { ... }); I read that this would force the page to load first, but to no avail...
What's the stupid detail I overlooked?!
Thanks to #guest271314, I learned a lesson in JS structure:
Previously, I had wrapped the entire code within the main document's script tag inside a $(function(){}; This I thought, was "necessary" as the script tag was placed inside the head element, and the document otherwise wouldn't have been ready.
When using another, external JS file however, this technique now prevented the external code from referring to functions declared inline, as these now "waited" for the rest of the document to be ready, including the external file (which then referred to a yet undeclared / "pending" main function).
Wow.
Removing the $(function(){}; wrap and moving the script element to the bottom of the body resolved the issue. I guess that's where it should've been in the first place... level up
Does $(document).ready(function() { means all javascript file has been downloaded so any js init or func should work?
so it is a good practise to always put js inside $(document).ready(function() { ?
$(document).ready is part of the page lifecycle and runs after all of the resources have been loaded for the page (HTML, CSS and JS files).
You should be functions in here that you need to run when the page first loads, so generally initialization of plugins, first run functions and attaching events to elements.
Any other functions that can run after the page has loaded can be defined outside of this scope.
Note that if you are dynamically inserting DOM elements, any events attached to that type or class (for example) will not be attached to them without re-attaching, or using .on and attaching to the document itself.
Use ready() to make a function available after the document is loaded:
for eg:
$(document).ready(function(){
$("button").click(function(){
$("p").slideToggle();
});
});
Definition and Usage
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. Like in the example above.
The ready() method specifies what happens when a ready event occurs.
note: The ready() method should not be used together with <body onload="">.
From jQuery documentation:
Description: Specify a function to execute when the DOM is fully loaded.
It means that you can specify a function to run after the DOM is fully loaded, ie is available to interact with javascript.
Following is copied from here
$(document).ready(...)
Fire when all DOM loaded (even if multimedia no loaded yet)
$(window).load(...)
Fire when all content loaded (progress indicator which shows loading proccess) gone.
Now here is my suggestion (not from that link)
I think the better approach would be putting your script tags at the end of body, like this, as it makes sure that the script is loaded when everything else has been loaded
<html>
<head></head>
<body>
<div>
bla bla bla
</div>
<script src="1"></script>
.
.
<script src="n"></script>
<script>console.log('hello');</script>
</body>
</html>
I have a javascript function, "loadFramework()" that modifies an HTML document. Specifically, it repeatedly runs the jQuery command $("#element-id").load("document/name.html"), which injects the HTML in document/name.html directly into the element with #element-id.
Originally, I ran loadFramework() in a script in the document's header. However, since then I've realized that the function fails if the page has not loaded yet, since it relies on there being an element with #element-id.
I can't figure out how to get this function to run when it should. A simple solution seemed to be setting it to be the document.onload function:
document.onload = function() {
loadFramework();
}
But in this case it never seems to run at all.
How do I make sure a header function runs only after the document has loaded?
You should use window.onload if you are looking for a vanilla JS option
window.onload = function() {
loadFramework();
}
Jquery load takes additional argument "complete". You can run the javascript there. So the code would be:
$("#element-id").load("document/name.html", function(){
loadFramework();
});
You can also use $(document).ready(function{loadFramework()}) inside the html you are loading.
If you want to execute the loadFramework() method after "document/name.html" is loaded, I would suggest the following code.
$(function() {
$("#element-id").load("document/name.html", function(){
loadFramework();
});
});
I'm just messing with some javascript and I came across something that puzzled me a little.
I've added a link to a script file into the header of a document, just after the link to jQuery.
If I place in the test file:
(function($){
$("#thing").mouseover(function(){alert("woo");});
})(jQuery);
The mouseover event does not trigger the function.
However, if I add
(function($){
$(document).ready(function(){
$("#thing").mouseover(function(){alert("woo");});
});
})(jQuery);
The event does work.
Is it simply that without $(document).ready the DOM hasn't finished loading at the point when my self-executing function runs, so there is no #thing yet to attach the function to or is there another explanation?
I've added a link to a script file into the header of a document
This is the point.
Usually people put script files in the footer of document to optimize the process of loading the page, therefore it would not need to wait for the document to be ready to execute something based on the DOM already loaded (if you are in the footer, you have already loaded the rest - unless you have some content loading async).
Try putting your script file in the footer, and you will not need the $(document).ready.
Summary: In your case you need it, because when the script starts executing you have not started yet looking for the DOM, and the element cannot be found in that time.
It's because document ready waits until the document has fully loaded before executing.
Anything that binds to DOM elements must be done when the document is fully loaded otherwise those event handler bindings will be trying to bind to DOM elements which don't yet exist.
So yes, you answered your own question.
$( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute
It waits for the entire HTML excepts the Images.
some times you noticed that you recived an error “$ is not defined.” then in that case
you can use $( document ).ready()
You can just move the $ to make it work
$(function(){
$("#thing").mouseover(function(){alert("woo");});
});
Demo
Explanation $(function(){}); is equivalent to $(document).ready(function(){}); in jQuery
The document ready function waits for the page to load and
then executes whatever is in there. This prevents immature
actions before the page loads.
As a thumb rule, remember this,
$(document).ready(function(){
//jQuery code goes here
});
Apparently this works for me
<div id="body">
<section class="featured">
<div class="content-wrapper">
...
</div>
</section>
</div>
#section scripts{
<script type="text/javascript">
(function ($) {
$(".featured").mouseover(function () { alert("woo"); });
})(jQuery)();
</script>
}
it is basically a immediately executing function.