Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css() and opacity.. following fadeIn() not working

Tags:

jquery

when I set opacity to 0 in css() the following fadeIn() doesn't work

if I set opacity to 1 the loader element is showed but there will of course not be any fading in..

loader.css({
        top : ($(window).height() - loader.height()) / 2+'px',
        left : ($(window).width() - loader.width()) / 2+'px',
        opacity : 0
    })
    .fadeIn(1000);

if I use display:none it works!?

loader.css({
        top : ($(window).height() - loader.height()) / 2+'px',
        left : ($(window).width() - loader.width()) / 2+'px',
        display : 'none'
    })
    .fadeIn(1000);
like image 312
clarkk Avatar asked May 18 '11 13:05

clarkk


People also ask

How to add fading effect CSS?

In the CSS, use the @keyframes rule paired with fadeIn. At 0%, set the opacity to 0. At 100%, set the opacity to 1. This creates the fade-in effect.

How to use fadeTo in jQuery?

jQuery | fadeTo() with Examples The fadeTo() is an inbuilt method in jQuery which is used to change the opacity of the selected element. Here selector is the selected element. speed: It specifies the speed of the fading effect. opacity: It specifies to fade and this value should must be in between 0.0 and 1.0.

What is fadeIn in JS?

The fadeIn() method gradually changes the opacity, for selected elements, from hidden to visible (fading effect). Note: Hidden elements will not be displayed at all (no longer affects the layout of the page). Tip: This method is often used together with the fadeOut() method.


2 Answers

Try using fadeTo()

loader.css({
    top : ($(window).height() - loader.height()) / 2+'px',
    left : ($(window).width() - loader.width()) / 2+'px',
    opacity : 0
})
.fadeTo(1000, 1);
like image 61
wdm Avatar answered Oct 05 '22 10:10

wdm


The problem is that jQuery only does functions like fadeIn if the element is not visible. jQuery internally does $(this).is(':hidden') to decide whether or not to run the animation. The hidden filter clearly does not check to see if opacity is 0; it probably should.

The obvious solution is to set display: none as you have, or to call hide() before your call to fadeIn() if you are sure the element is hidden.


The other solution is to redefine the hidden filter to check for opacity:

jQuery.expr.filters.hidden = function(elem) {
    var width = elem.offsetWidth,
        height = elem.offsetHeight;

    return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css(elem, "display")) === "none" || (elem.style.opacity || jQuery.css(elem, 'opacity')) === "0");
};

Running .is(':hidden') will now check for opacity. See jsFiddle.


I've filed a bug report to cover this issue.

like image 20
lonesomeday Avatar answered Oct 05 '22 11:10

lonesomeday