The correct way to fade in/out different blocks in the same space

By : n0pe
Source: Stackoverflow.com
Question!

I have a collection of buttons arranged horizontally across the screen and below those buttons is a space where I want different kinds of content to appear. For example, if I have a button named "biography" and I click on it, I would like a block containing biography text to fade in. If I then click on "pictures", the biography block should fade out and the pictures block should fade in.

The current solution that I have (and I know it's wrong) is as follows. Below my buttons I have a table with rows corresponding to the different blocks that I want to display, like this:

+---------------------+
|                     |
|      biography      |
|                     |
+---------------------+
|                     |
|      pictures       |
|         ...         |

I set them all to display: none in my stylesheet and then when a button is clicked, I fade out all of the rows and fade in the one that I want displayed. It isn't clean and it probably isn't the best way to do things.

Here's the jQuery code that I have:

var blocks = [
     "projects-fade",
     "blog-fade",
     "online-fade",
     "resume-fade"
]

$("#projects").click( function()
{
    // Fade out all blocks
    $.each(blocks, function()
    {
       $("#" + this).fadeOut(100);
    })
    // Fade in the correct block
    $("#projects-fade").fadeIn(300);
});
// the code above is repeated for each button

In the code #projects is a button named "projects", and blocks is an array containing the ID's of all the text containers that appear in the space below the buttons. As you can see in the code, when #projects is clicked, all the blocks fades out (in the event one is open and taking up space) and then it fades in the relevant block (in this case #projects-fade).

How can I achieve this in a better way?

By : n0pe


Answers

If you don't have all your buttons/links inside a container already, then put them inside a div and give it the ID menu. Then do the same with your "blocks", but give that container the ID blocks. When that's done, change your JQuery code to this:

$("#menu a").click(function()
{
    // Assuming the buttons have the same id's as the blocks, minus "-fade"
    var blockID = $(this).attr("id")   "-fade";

    // Fade out the active block
    $("#blocks .active-block").fadeOut(300, function()
    {
        $(this).removeClass("active-block");

        // Fade in the new block
        $("#"   blockID).addClass("active-block");
        $("#"   blockID).fadeIn(600);
    });        
});

It's similar to your current code, but it's pretty much all you can do if you don't want to use AJAX.

By : Tom


This video can help you solving your question :)
By: admin