I am trying to show a busy waiting icon at the point of ajax invocation (i.e., event.target
or object that fired the event). I use the following code to achieve that but in some cases the position (offset) of the element returned is top:0
and left:0
- I know I'm probably making a mistake but can't seem to nail it. Here's my code (It's in a backbone view class, but that shouldn't matter since it's quite trivial):
//ajax loading animation
var LoadingAnimation = Backbone.View.extend({
tagName: 'div', //creates an empty div element
initialize: function() {
var DOMElement = this.options.DOMElement; //is passed as a param (see below)
var pos = DOMElement.offset(); //<-- pos.left and pos.top 0 for some elements??
var _width = DOMElement.outerWidth(true);
var _height = DOMElement.outerHeight(true);
//setting the 'style' of 'this' div
$(this.el).css({
"position":"absolute",
"left" : pos.left+"px",
"top" : pos.top+"px",
"z-index" : 9999,
"width" : _width+"px",
"height": _height+"px",
"background": "#FFFFFF url(images/loading_round.gif) no-repeat center center"
});
/*appending to body. Don't know if this is correct, but nothing would
*show if it was not done :(
*/
$('body').append(this.el);
//_.bindAll(this, 'render','unrender'); //ignore for now
this.render();
},
render: function() {
$(this.el).show();
},
unrender: function() {
$(this.el).fadeOut("slow");
$(this.el).remove();
}
});
Here's how it can be invoked:
$('.ajaxAble').click(function(event){
var showBusy = new LoadingAnimation({DOMElement:$(this)}); //create and render busy waiting
//do ajax calls here and call showBusy.unrender() in success/error
}
This works fine for some elements but for some the offset() returns 0. I don't know why though? All of those elements have relative positioning and the div to be shown has absolute. But I don't see the conflict. (Is there one?). I need to make this class as position agnostic as possible, so to speak...
PS: I chose the local non-blocking way as pointed out in this post: Best way to have 'busy waiting' animation be 'position configurable' in jquery? (i.e., show it where the action is)
UPDATE: (After selecting answer): Tom's answer of appending to parent of DOMElement is correct. However for that to work properly it's better to use .position()
rather than .offset()
above (as suggested by rkw). The above code appends to body (incorrect for some elements) but uses offset.