How do I find if an element has been loaded using JQuery - javascript

I am loading data into the flexigrid. I am trying to use JQuery selectors to make the rows clickable, but I am unable to do so. I want to know if the element has been fully loaded, how do I do that?
I want to do something like if(element.load == true){//do this}. I am not sure of how to check that out. Could anybody help me with this.
Ok, so I already have this div, and am binding a flexigrid to that div. I want to know if the flexigrid has been bound.
$("#GridLoad").flexigrid();
I want to know if the flexigrid has been bound, after that, I need to run a piece of code.
Using a live() on div Gridload would always be true as it is already there. :(

I want to know if the element has been fully loaded?
There appears to be an onSuccess callback.
$("#GridLoad").flexigrid({
'onSuccess': function() {
// Do this.
}
});
Otherwise, if the things you are binding are being lost when the table updates, attach the events via on() or simply capture them at the persistent ancestor element and examine event.target.

You can use $(element).live('click', function () { // do something });
so that if it later loads it'll have the appropriate event binding.

you could use the callback function of jquery's load method.
like so :
$('#result').load('ajax/test.html', function() {
alert('Load was performed.');
});
Even if you are not using 'load' method, almost any method in jquery supports callbacks which happen after the functionality has been completed.
For example, ajax() has success and failure callbacks, animations has callbacks, etc.

Related

Jquery Onclick functionality not working for div, as specific loaded after sometime

For <div class="editdiv">Test</div>. Jquery click functionality is added in document.ready function . But editdiv loading in page dynamically with delay.
So when I click on the div. Function is not calling. By using timeout function is working fine.
I need a different approach to solve this functionality.
If your .editdiv is loaded dynamically after your js loading so your click event can't detect it and it will not work, instead you should use event delegation on() to deal with fresh DOM :
$('body').on('click', '.editdiv', function(){
//Your click event code
})
If you want to avoid setTimeout you could use delay with queue callback method :
$('div.scroll-area-blue')
.delay(5000)
.queue(function() {
$(this).enscroll({
showOnHover: false,
verticalScrolling: true,
verticalTrackClass: 'vertical-track-blue',
verticalHandleClass: 'vertical-handle-blue'
});
});
If you will use setTimeout better to use it like :
setTimeout( enscrollDiv, 5000);
function enscrollDiv(){
$('div.scroll-area-blue').enscroll({
showOnHover: false,
verticalScrolling: true,
verticalTrackClass: 'vertical-track-blue',
verticalHandleClass: 'vertical-handle-blue'
});
}
Hope this helps.
It is really difficult to understand whats going wrong from your question. What I guess is you are loading a specific div using Ajax or similar technologies - meaning the div is not available initially.
The way jQuery works is that, it only binds the event to the elements only available at the time the part is executed.
If a <div id='myDiv'></div> is not present when $('#myDiv').click(function(){}) is called, it won't work.
One workaround is to do it like this:
$('body').on('click','#myDiv',function(){});
This registers the click on body and then checks if the clicked element is having a id 'myDiv' or not. We can expect the <body></body> to be present always. So the problem we had with previous code won't happen here.
maybe you're loading the javascript codes before the html elements(tags) are loaded.
try adding the script which includes "document.ready()" before the end tag of the body when all html tags have already finished loading.
I'm hitting targets in the dark. Hope it works for you. It's difficult to generate any solution without analyzing the problematic code......

How to avoid multiple loading of jQuery functions?

I am using following code on my page which I am loading in ajax.
$(document).ready(function() {
$('#button_id').click(function() {
//Do Something
});
});
Now When I click on the button action happens multiple times. I know that its happening because I am loading the ajax page multiple times.
Please help me solve this.
You can use .off() to remove existing listeners:
$(function() {
$('#button_id').off('click').click(function() {
//Do Something
});
});
If I am wrong about your implementation I apologize. Your problem may exist because the binding is created on first page load and then on subsequent ajax loads with new scripts being inserted and creating duplicate bindings. You should prevent any bindings from being generated on ajax loads to prevent duplicate bindings unless you are good with cleanup.
If the button you are clicking on exists in the ajax loaded area then you should use delegation to ensure that the click handlers still work.
For example:
$( "body" ).on( "click", "#button_id", function() {
//do something
});
This will add a binding to the body element, but more specifically to the id #button_id. A click event on the button will propagate and bubble up to the body element (or whatever parent element you choose).
This makes it so that dynamic elements can be inserted in the DOM and only one event handler is needed to listen for it.
No need for .on() or .off() calls for individual ajax loads. This allows your bindings to be much cleaner.
Of course, if your button is not likely to exist on the page all the time then it would not be a good idea to keep extra bindings. Only create these types of binding if they are always needed to prevent optimization issues.
A cleaner solution would be to remove that code from the ajax loaded HTML and use one single event handler in the master page
I guess your problem is the event is firing many times.
To fire only once try this:
$(document).ready(function() {
$('#button_id').on("click",function(e) {
e.preventDefault(); // This prevents the default non-js action (very used for anchors without links or hashes)
e.stopPropagation(); // Prevent the bubling of the event and spread more times
//Do Something
});
});
If doesn't work with e.stopPropagation(); try with e.stopInmediatePropagation();
Adding documentation for the last method I suggested. It could solve your problem.
http://api.jquery.com/event.stopimmediatepropagation/

Using jQuery .on() for all events

Is it considered bad practice to use jQuery's .on() event handler for every event?
Previously, my code contained script like this:
$('#cartButton').click(function(){
openCart();
});
However I've recently started using InstantClick (a pjax jQuery plugin).
Now none of my scripts work. I understand why this is happening, but I cannot wrap my code with the InstantClick.on('change', function(){ tag as this means my code starts to repeat itself. For example, clicking on the cart button will run the openCart() function many times. So to get around this, I'm changing all my functions to something like this:
$(document).on('click', '#cartButton', function(){
openCart();
});
I'm curious as to whether this will increase loading times and cause excess strain. Is it bad practice to use the on() event handler for every event in my code?
It's not bad practice at all..
.on is the preferred method for handling all events, and using .click is just a shortcut that gets passed to the .on method anyway..
If you check out here (unminified source for jquery 2.1.0): https://code.jquery.com/jquery-2.1.0.js
Here are a couple notes:
search for this line: on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
This is the function definition for the on method and just shows you what the code is doing..
also search for this line: jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick "
Th code below this line is mapping all the directly callable shortcuts (like click) and shows you that they are just mapping to the 'on' method.
Hope this helps!!!
No it is not a bad practice to use .on(), actually if you check the source of the .click() function, you'll see that it actually calls .on().
But... Instead of creating an anonymous function, you should simply do this, which would be cleaner, and slightly faster:
$(document).on('click', '#cartButton', openCart);
and
$('#cartButton').click(openCart);

Can jQuery ready() function be used twice for the same element?

I want to use jQuery ready() function for the document element. Here are my scripts:
1st page:
$(document).ready(function(){
$('form#haberekle').ajaxForm(options);
});
2nd page:
$(document).ready(function() {
var options = {
success:showResponse,
beforeSubmit:showRequest,
resetForm:true
};
$('#haberresmiekleform').ajaxForm(options);
});
These two pages are included in the same main page with <!--#include file=""-->
Can these two functions work properly, or they block each other?
According to my experience they seem work properly.
For example: an onclick function of a button is only one.
You can have as many .ready() calls as you want, jQuery is designed with this in mind and it's absolutely ok.
So yes, it is ok, and you won't have any problems...this happens all the time.
Think of it as an event handler, like .click(), this is exactly how it behaves (well, strictly speaking, not exactly, but for most purposes like this). So you can have as many as you want.
One more note that may be of interest, the handlers you pass into .ready() are pushed via .done() to the readyList, which means they'll execute in the order you called them in the page. The same order behavior is true (though via an array, a different method) in earlier versions of jQuery.
Yes, that is fine. Both will be called when the dom is fully loaded. Note that if you call .ready() after the dom is already loaded, the callback will be executed immediately. See http://api.jquery.com/ready/
Yes, you can.
Take a look here:
http://www.learningjquery.com/2006/09/multiple-document-ready
No problem attaching several handlers for the same event. The documentation for ready says :
There is also
$(document).bind("ready", handler).
This behaves similarly to the ready
method but with one exception: If the
ready event has already fired and you
try to .bind("ready") the bound
handler will not be executed.
And the documentation for bind says:
When an event reaches an element, all
handlers bound to that event type for
the element are fired. If there are
multiple handlers registered, they
will always execute in the order in
which they were bound

Issue with binding in jQuery for copied elements

This is actually a bigger question because I know there are several ways to solve this problem but I will try to sum it up.
What I try to do: I am using this jQuery plugin to upload files via Flash http://www.uploadify.com/. However, the element #fileInput that I supposed to bind this function to is a live element which is generated after the page loaded: $('#fileInput').uploadify(). The reason #fileInput is a live element is because I use FancyBox to popup a DIV and this FancyBox basically just "cloned" the inner html of the DIV.
What happened: When I clicked "BROWSE" to upload a file, there is no progress bar for upload. The reason is because the Uploadify could not bind to live elements.
Questions:
1. I tried to replace bind() with live() in uploadify code but that did not work because bind() allows to pass [data]. The LiveQuery plugin http://docs.jquery.com/Plugins/livequery does not have the same syntax as bind() either. Is there anything similar to bind but works for live elements?
If I don't try to replace bind() function and keep uploadify code the same. Does anyone know how to change code in FancyBox so that it WILL NOT make a clone to generate live elements? I know this is a hard question too.
Note: FancyBox site seems dead --> http://www.visual-blast.com/javascript/fancybox-jquery-image-zooming-plugin/
Thank you very much!
You might consider changing the FancyBox code to support calling a callback function after it clones the HTML. Then, put the uploadify() call in the callback function.
You could overload the live method, making it support data as the second parameter:
jQuery.fn.live = (function(_live){
return function( type, data, fn ) {
var _fn;
if ( jQuery.isFunction(fn) ) {
_fn = function(e) {
e.data = data;
return fn.call( this, e );
};
}
return _live.call( this, type, _fn || fn || data );
};
})(jQuery.fn.live);
Replacing all instances of bind(...) with live(...) should now work.
Note: you'll have to put the overloaded method above everything else.
From my experience , the only way I have found to do this is by using livequery
It has a similar syntax, and in your case to bind uploadify on a live element, you would use
$('#fileInput').livequery(function(){
$(this).uploadify();
})
Livequery accepts functions without events, and executes them everytime there is a change in the DOM
How is the element generated? If its fetched from the server using jQuery you can use a more hackish way of fixing it, simply put jQuery runs eval() on any script tags it runs into so you could just put:
<script type='text/javascript'>
$(function(){
$('#fileInput').uploadify();
});
</script>
In the fetched html and it'll bind it on load instead of trying to watch over it live. Bonus points, if you fetch the html again it'll be unbound.

Categories