Search code examples
javascriptjqueryhtmljquery-traversing

jQuery Traversing and simple code?


Okay, before I ask this question. Let me explain my goal: I want to write as little code as possible, and still be able to have tons of functionality at the same time. I have coined this as 'beautiful code' to myself and colleagues.

Here's the problem: I want to click a box, and a panel to fade in with the desired content based on which box I clicked. Except that I cant use two classes and cannot re-use id's.

Here's the code: http://jsfiddle.net/2Yr67/

$('.maingrid').click(function(){
    //'maingrid' fade out
    //'panel' fade in with proper content
});

I had two ideas that would please me.

A) Have one panel fade in, and content fill into the panel based on which 'maingrid' box that was 'click'ed B) Have a specific panel with the content fade in, based on which 'maingrid' was selected

I'm not asking for you to do it for me, simply push me towards the syntax needed to do what I want

Thanks in advance!


Solution

  • The first thing to do is to move your panel HTML elements closer to the maingrid elements. This allows you to hide/show the correct elements in order. Having all of the panels in their own separate element causes you to do DOM manipulation should shouldn't need to do. For simplicity, I put each panel right after the maingrid element that it was associated with it.

    HTML Structure

    <div class=".mainContainer">
       <div class='maingrid'></div>
       <div class='panel'></div>
       <div class='maingrid'></div>
       <div class='panel'></div>
       <div class='maingrid'></div>
       <div class='panel'></div>
       <div class='maingrid'></div>
       <div class='panel'></div>
    </div>
    

    I added the panel class to have the same CSS as maingrid, as well as make it invisible at the start:

    .maingrid, .panel {
        height: 345px;
        width: 345px;
        float: left;
        /* [disabled]background-color: #000; */
        margin-top: 5px;
        margin-right: 5px;
        cursor: pointer;
        overflow: hidden;
    }
    .panel{
        display:none;
        color:white; 
    }
    

    This will fade out the current element clicked and fade in the next panel element.

    $('.maingrid').click(function(){
            var $that = $(this);
            $(this).fadeOut(function(){  //This will wait until the fadeOut is done before attempting to fadeIn.
                $that.next().fadeIn();
            });
        });
        $('.panel').click(function(){
            var $that = $(this);
            $(this).fadeOut(function(){
                $that.prev().fadeIn();
            });
        }); 
    

    There also seems to be a bug where the hover does not show the text on the first hover event.

    JSFiddle: http://jsfiddle.net/mDJfE/