Simple questions about ajax - Help me understand - javascript

I need a little help understanding something. I am using the colorbox plugin to load an external an external html snippet (which works fine). But none of my jquery selectors see the newly loaded html. Is that right (I think it is)? and if so how do I work around that.
Thanks

When you set any properties/bind events in your $(document).ready(function() { ... }) they are executed on page load. So it is all applied to the DOM elements that are present initially.
But when you call the AJAX request and insert some elements into your document, the jquery statements are not executed again (because document.ready doesn't fire). Some solutions to overcome this are:
execute the inside of the document.ready function or the relevant part of it after you insert the new elements.
if the only thing you need are event handlers that should be bound the the new elements you may use live events.

Related

How important it is to wrap jquery code in $(document).ready() function?

I have been developing my frontend code with jQuery for a while now, and since I am implementing the site with partials in rails. Often I would use content_for :javascript to wrap up some code that is specific for a view.
and my question is, I end up with a lot of script tags and since most of them are jquery code, I have typed up a lot of $(document).ready(function() {});
So my question is, whether it is necessary to wrap everything in document.ready, and if I have too many of document.ready will it affect the performance?
$(document).ready() has one purpose - to execute some code after the DOM has finished loading and is now ready for access or modification.
If your code is located before DOM elements such as in the <head> tag or in the top or middle of the <body> section before some DOM elements and that code does attempt to access the DOM upon first initialization, then it should be placed into a $(document).ready() block so it will not execute before the DOM is ready or the ` tag should be moved.
If your code is in a <script> tag within the <body> that is after the DOM elements that it needs to access then your code does not need to be in a $(document).ready() block.
Or, if your code is not called upon initialization (e.g. it's only called later upon other events) or your code does not access the DOM upon initialization, then that code does not need to be inside a $(document).ready() block.
Though you obviously have jQuery available, you can read this answer for a more detailed description: pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it.
Having multiple $(document).ready() blocks is just like registering multiple callbacks for an event. It's really no big deal. Each one just takes an extra couple function calls to setup and is an extra callback execution at execution time. If that's the cleanest way to write your code, then by all means use multiple $(document).ready() blocks.
To summarize, put code into a $(document).ready() block when:
A specific block of code needs to access the DOM when it is first run and the code is located in a script tag that is placed before the end of the <body> tag or is placed before some DOM elements that it might need to access.
There is no need to put code into a $(document).ready() block when:
The part of the code that runs at first initialization does not access the DOM.
The code is placed into a <script> tag that is after the DOM elements that it references.
The <script> tag is marked defer because this explicitly instructs the browser to delay the running of this script tag until after the DOM has been parsed.
Also, keep in mind that it does not matter where functions are declared. It only matters where the functions are called from. So, you can define as many functions as you want outside of $(document).ready(). You just have to make sure that any functions that access the DOM are not called too soon.
If your code does access your DOM element but you put it outside $(document).ready(), it may subject to fail or produce unexpected behavior. See this example below:
var listA = $('ul.myclass').children();
$(document).ready(function(){
var listB = $('ul.myclass').children();
});
From simple snippet above, listA is calculated straightaway when the script is loaded even your document has not been fully loaded or ready, while listB is calculated when the document is loaded and ready.
listA and listB could be different in this scenario even though they are calculated from the same DOM selector.
It's OK for you to initialize some variable values or pre-load some values which have nothing to do with the UI outside of document.ready(). But when you want to initialize your UI or access the DOM upon startup, always do it when the document finishes loading (document.ready).
I agree with everything #jfriend00 says but also remember that not all your code needs to be in the document.ready event. What I mean by that is that you can create your functions at any time, they only need to be executed at document.ready. For instance:
function manipulateDOM( el ) {
document.getElementById(el).classList.add('myClass');
}
$(document).ready(function()){
manipulateDOM('myEl');
});

Binding any bootstrap to dynamic HTML

My question is not about binding a single event to a specific DOM element. My question is, how can you rebind your whole bootstrap library to dynamically generated DOM elements?
For my case I am using the Jquery method .load and I would like to rebind the HTML loaded by that method to my Metro UI bootstrap library. I don't think going to the loaded HTML, checking all the events and components used and re-binding them is an effective solution. I might as well prefer somehow refreshing all bindings after loading the dynamic HTML (if that is also possible). Any help there? Thank you!
After a while of trying I finally found a way to execute the script. I added another method to the callback function to the .load method:
$("#id").load( "dynamic.html", function(){
$.getScript("boostrap.js");
} );
It may not be the most effective way to rebind elements, but at least I make sure all the JS code is re-binded as if the HTML had been loaded from the initial load.

Necessity of .ready() in jQuery

I've seen various examples use this and I'm curious to know, is it dangerous not to wrap jQuery code in the following?
$(document).ready(function () {});
I know what it does and I know why you do it but I'm curious if it is more unsafe or just bad practice/style to not have it? Thanks!
You use it if your code needs to access the DOM.
If you're just setting up classes and modules, but not actually running them, then you don't need to wrap them in the ready handler.
However, if you're doing something that requires elements to be loaded (like, adding event handlers) then you need to do it in the ready() event.
EDIT:
Here is an example: http://jsfiddle.net/ctrlfrk/43n8U/
Try commenting out the addHandler functions and see what happens.
(Note that I've set jsfiddle to run this code in the head tag, by default it usually places the code in the onload event, which negates the need for the ready handler)
It depends on where you are placing your scripts. If you add a script tag just before the closing <body> you don't need to use it because the DOM will already be loaded. On the other hand if you place your script tag inside the <head> section and access the DOM you absolutely need to use it or your script won't work because at the moment your script executes the browser hasn't yet read and parsed the DOM.
See this (already answered)
jQuery ready function aliases
for those that the above is tl;dr; :
Additional reading: http://api.jquery.com/ready/
Wrapping your code in ready() function only delays the running of that code until the page has been loaded. The code does not get "safer" somehow.
But many times you want to run some code that will query the DOM that is created after the script-tag that your code is in, or simply need some structures from the document that are placed after that script tag. If that is the case, then ready() is for you.
But generally there is no valid reason not to use ready() function, so that's why everybode almost always use it.
I think you should also be aware of jQuery's $(window).load() and how it differs from $(document).ready()
Read more about it here

How to not use JavaScript with in the elements events attributes but still load via AJAX

I am currently loading HTMl content via AJAX.
I have code for things on different elements onclick attributes (and other event attributes).
It does work, but I am starting to find that the code is getting rather large, and hard to read. I have also read that it is considered bad practice to have the event code 'inline' like this and that I should really do by element.onclick = foobar and have foobar defined somewhere else.
I understand how with a static page it is fairly easy to do this, just have a script tag at the bottom of the page and once the page is loaded have it executed. This can then attach any and all events as you need them.
But how can I get this sort of affect when loading content via AJAX. There is also the slight case that the content loaded can very depending on what is in the database, some times certain sections of HTML, such as tables of results, will not even be displayed there will be something else entirely.
I can post some samples of code if any body needs them, but I have no idea what sort of things would help people with this one. I will point out, that I am using Jquery already so if it has some helpful little functions that would be rather sweet!
Small code sample
This is a sample of code that is loaded via an AJAX request
<input type="submit" name="login" value="login" onclick="
if(check_login(this.form)){
Window_manager.windows[1].load_xml('login/display.php?username=' + this.form.username.value + '&password=' + this.form.password.value);
} else {
return false;
}">
I know this is small sample, but this is the sort of thing I am on about. How can I have this code attached when the content is loaded?
jQuery .live() method is probably what you are looking for. It will attach click event to newly created HTML elements, so you don't need to call your .click() with every reload of your update-panel.
You can get cleaner HTML code by making the event bindings in javascript. All you need are ways to identify the DOM objects for your HTML elements, like IDs.
If you have a link that has an ID "fooLink" you can do this in your JavaScript:
docuemnt.getElementById('foo').onclick = function () {
//do your stuff here
}
This will have the same effect as binding the event in the "onclick" attribute if the link element in your HTML code.
That way, you can produce much cleaner HTML that is easier to read and maintain.

How do you use $.getScript with ajax content?

I am loading an external page that relies heavily on jquery into a div with the $.ajax(); method.
The obvious problem is that the new content needs to be binded to the dom for jquery to work... Everyone talks about just using $.getScript to do this but I can't get it to work. Can some one give me an example and not just a link to the jquery doc page for $.getScript ?
This external page has 6 js files included in it and I need them all binded to the new content as a whole and not per div as in all of the examples I can find.
"new content needs to be binded to the dom for jquery to work"
I assume that you mean that the events binded on elements do not work for the dynamically loaded content. If this is the case, you must bind the elements with live() method. So instead of:
$('#element').click(function() { ... });
Do:
$('#element').live('click', function() { ... });
This way your binds will also affect the loaded content.
If you understood your problem wrong, please let me know.

Categories

Resources