Kuba Orlik
Kuba Orlik

Reputation: 3500

How to fade in a table using jQuery

I want to create a page where a table would be faded in as it loads (from transparent to opaque). I've tried using:

$(document).ready(function(){
    $('#table1').hide();
    $('#table1').fadeIn(1000);
  });

And it kind of works, but the table shows up, quickly disappears and then smoothly fades in. Is there a way to achieve the fadein without the table appearing beforehand?

Upvotes: 2

Views: 9311

Answers (6)

Roko C. Buljan
Roko C. Buljan

Reputation: 206078

What is happening:

  • the table is 'display:table;' by default.
  • the browser reads the DOM and displays the table
  • jQuery hides the table and does the animation

Set inside your CSS display:none; for your table:

#table1{
   display:none;
}

jQuery:

$('#table1').fadeIn(1000);

Upvotes: 5

gaurang171
gaurang171

Reputation: 9080

Here is complete solution for fade In your table using jQuery.

1) Include latest jQuery.js and JQuery-UI java script files in header tag first.

2) HTML:

<table id="table1" cellpadding="5" cellspacing="1" width="50%">
  <tr>
    <th>
      Column1
    </th>
    <th>
      Column2
    </th>
    <th>
      Column3
    </th>

  </tr>
  <tr>
    <td>
      data1 
    </td>
    <td>
      data2 
    </td>
    <td>
      data3 
    </td>
  </tr>
</table>

3) CSS:

#table1{
  border:1px solid #556688;
  background:#eee;
  display:none;
}
th{
  text-align:left;
}
td,th{
  border:1px solid #556688;
}

4) JQuery in script tag:

$(document).ready(function() {
    $('#table1').fadeIn(10000);
});

Try it on bins: http://codebins.com/bin/4ldqpaj

Upvotes: 1

Chrisissorry
Chrisissorry

Reputation: 1514

The table shows up in the first place because Javascript is executed after the DOM is loaded. You should hide the table initially by using display:none in your css.

Upvotes: 0

JohnC
JohnC

Reputation: 1387

You could achieve this by applying a

display:none

style to the table, however this then draws accessibility issues as users without javascript won't be able to see it.

Upvotes: 3

Mihai Stancu
Mihai Stancu

Reputation: 16107

Use dispay:none in your CSS to have the table hidden before fading it in.

Upvotes: 0

Fraser
Fraser

Reputation: 14244

Yep. Just set your table to display:none in your CSS and then remove the initial hide

CSS

#table1{display:none}

jQuery:

$(document).ready(function(){
    $('#table1').fadeIn(1000);
})

The jQuery is not fired until the whole page and it's dependencies have loaded (the $(document).ready function) but the table is shown on the page as soon as it has loaded which will always be before the jQuery fires. Once the jQuery fires, it hides the table and then fades it back in. You just need to hide it with the CSS and then fade it in. Easy :)

Upvotes: 1

Related Questions