Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery animate opacity vs display:none

If a element has a display:none on it in the CSS, then animating the opacity from 0 to 1 in jQuery doesn't make the element visible.

why?

what do I need to add in animate() to make it visible?

el.css({
            opacity: 0,
            left: - 200
          }).stop().animate({
            opacity: 1,
            left: 0
          }, {
            duration: 333
          });
like image 202
Katy Avatar asked Jun 26 '11 18:06

Katy


People also ask

Is opacity 0 the same as display none?

As you can see, whenever you need the element to disappear completely and not take up any space, you should use display: none; . If you want the element to have a transition or fade-in effect when becoming visible, you should use opacity: 0; .

Is there a difference between display none and opacity 0 in CSS?

opacity:0 will still allow click, hover, and other mouse events on the element. It just won't be visible to the user. display:none does what it implies—the element still exists but is completely not visible, as though it's width and height are 0.

What does jQuery show() do?

show() method animates the width, height, and opacity of the matched elements simultaneously.

What is opacity in jQuery?

jQuery Effect fadeTo() MethodThe fadeTo() method gradually changes the opacity, for selected elements, to a specified opacity (fading effect).


1 Answers

You'd need to show it first using the show()[docs] method.

If your element isn't already at opacity 0, then you'd probably want to set that first:

.css('opacity',0).show().animate({opacity:1});

Example: http://jsfiddle.net/DnE7M/1/


Or you could just use the fadeIn()[docs] method, which should take care of the display as well.

Example: http://jsfiddle.net/DnE7M/


EDIT: To make it relevant to the code added to the question:

el.css({
        opacity: 0,
        left: - 200
      })
   .stop()
   .show()     // <-- make the element able to be displayed
   .animate({
        opacity: 1,
        left: 0
      }, {
        duration: 333
      });

You could also do it right in the call to the css()[docs] method:

el.css({
        opacity: 0,
        display: 'block',  // <-- 'block' or whatever is appropriate for you
        left: - 200
      })
   .stop()
   .animate({
        opacity: 1,
        left: 0
      }, {
        duration: 333
      });
like image 198
user113716 Avatar answered Nov 09 '22 09:11

user113716