Reputation: 27301
I am trying to show a loading image (and turn the parent transparent) for a page with many AJAX requests. What would be the most efficient way to add/remove the loading icon and opacity for each div independently?
Here is what I have so far. The problem with my approach is that the opacity is applied to the gif too, which is not what I want. Is there an easy fix to my code or a better approach to this?
Example: http://jsfiddle.net/justincook/x4C2t/
HTML:
<div id="a" class="box">A</div>
<div id="b" class="box">B</div>
<div id="c" class="box">C</div>
JavaScript:
$.fn.loading = function(show){
if(show){
this.prepend('<div class="loading-centered"></div>');
this.css({ opacity: 0.3 });
}else{
this.children('.loading-centered').remove();
this.css({ opacity: 1 });
}
};
$('#a').loading(true); //start
setTimeout(function(){ $('#a').loading(false); }, 3000); // stop
Upvotes: 2
Views: 3188
Reputation: 136
I would keep the styling in the CSS and just use JS to inject / remove the element http://jsfiddle.net/x4C2t/7/
$.fn.loading = function(show){
if(show){
this.prepend('<div class="loading-centered"></div>');
}else{
this.children('.loading-centered').remove();
}
};
css:
.box {
float:left;
width:100px;
height:100px;
border:1px solid #bbb;
margin: 10px;
padding:20px;
text-align:center;
border-radius:10px;
background: #eee;
position: relative;
}
.loading-centered {
background:url('http://www.ajaxload.info/images/exemples/24.gif') center center no-repeat white;
position:absolute;
height: 100%;
width: 100%;
top: 0;
left: 0;
border-radius:10px;
zoom: 1;
filter: alpha(opacity=50);
opacity: 0.5;
}
Upvotes: 5
Reputation: 2103
Opacity applies to an elements children as well. Instead of using opacity just make the background of the parent have more opacity with rgba colors. Here is an example. Also you were using
setInterval(function(){ $('#a').loading(false); }, 3000);
When you should have done
setTimeout(function(){ $('#a').loading(false); }, 3000);
That was causing the page to crash for me.
Upvotes: 0