Samantha J T Star
Samantha J T Star

Reputation: 32758

How can I turn a background visibility on and off with jQuery?

I have the following CSS:

#load-icon
{
    background: url(/Images/loaders/mask-loader.gif);
    background-repeat: no-repeat;
    z-index: 99; width: 32px; height: 32px;
    z-index: 99; 
    margin-top: 9px;
    margin-bottom: 9px;
    margin-right: 5px; 
    display: none;
}

I was using the following code to make it visible and not-visible:

$(document).ajaxStart(function () {
    $('#load-icon').show(500);
});
$(document).ajaxStop(function () {
    $('#load-icon').hide();
});

However the background is used for spacing and when it is hidden then the #load-icon uses no space which is not what I want.

How can I make it so that the #load-icon always uses space of 32px and the gif just becomes visible or not visible? If it makes it easier I am not too concerned about fade-in or fade out durations.

Here's a fiddle that shows where it is used: fiddle

Update: I really need a way that does not involve setting the background image to none and then back to the gif. That's because I may well be using different CSS styles and I can't code the gif name into my javascript.

Upvotes: 0

Views: 442

Answers (2)

DannyTheDev
DannyTheDev

Reputation: 4173

you should set in jquery background none.. i.e

$(document).ready(function(e) {
    var loadicon = $('#load-icon').css('background');
    $('#load-icon').css('background','none');

    $(document).ajaxStart(function () {
        $('#load-icon').css('background',loadicon);
    });
    $(document).ajaxStop(function () {
        $('#load-icon').css('background','none');
    });
});

Upvotes: 2

yckart
yckart

Reputation: 33378

$(document).ajaxStart(function () {
    $('#load-icon').fadeTo(0,0.0);
});
$(document).ajaxStop(function () {
    $('#load-icon').fadeTo(0,1.0);
});

Upvotes: 1

Related Questions