Search code examples
jqueryfadeinfadefadeout

fade out div before another fades in — Jquery


I'm very new at this jquery business — if you can find it in your hearts to forgive me and my ignorant questions, I'd be very grateful.

My dilemma: I have two divs, and I need one to fade out before another fades in.

Here is my code:

<script type="text/javascript">
  $(document).ready(
    function(){
        $("#about").click(function () {
            $("#aboutinfo").fadeToggle();
        });
    });
</script>
    <script type="text/javascript">
  $(document).ready(
    function(){
        $("#contact").click(function () {
            $("#contactinfo").fadeToggle();
        });
    });
</script>

The website in question is this.

Also, I take it I have written that jquery wrong, because both statements have their own <script></script> tags?

Thanks to whoever can help :)

edit: this seems to not be working:

<script type="text/javascript">
  $(document).ready(
    function(){
        $("#music").click(function () {
            $("#musicinfo").fadeToggle();
            $("#about").click(function () {
            $("#aboutinfo").fadeToggle();
            $("#contact").click(function () {
            $("#contactinfo").fadeToggle();
        });
    });
</script>

Solution

  • The animations all accept callback functions that will be called as one animation finishes:

    $('#about').click(function() {
        $('#contactinfo, #musicinfo').fadeOut(function() {
            $('#aboutinfo').fadeIn();
        });
    });
    

    If there is nothing to fade, (i.e. no visible elements), the callback will fire immediately.

    ... and yes, this could all be within one <script> block, and within one $(document).ready listener:

    $(document).ready(function() {
       $('#about').click(function() { ... });
       $('#contact').click(function() { ... });
    });
    

    If you used classes as well as IDs, you would probably be able to write a single click handler for all elements. Something like:

    $('.header-item').click(function() {
       var target = $('#' + this.id + 'info');
       $('.info-item').not(target).fadeOut(function() {
          target.fadeIn();
       });
    });