Search code examples
jqueryhtmlfilterswitch-statementparents

Looking to optimize the following JQuery code


I have 4 floated divs, when you hover over the A tag inside the divs, a div will show up at the bottom of these 4 divs which corresponds to the div where the click happenned. I have optimized the JQuery to the best of my knowledge, but I just wanted to see if there are other solutions out there.

My Fiddle: http://jsfiddle.net/jonxblaze/PyHH5/

HTML

<div class="wrap">
<div class="promo red">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>

    <p><a href="#">More</a></p>
</div> 
<div class="promo yellow">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>

    <p><a href="#">More</a></p>
</div>    
<div class="promo blue">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>

    <p><a href="#">More</a></p>
</div>
 <div class="promo black">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>

    <p><a href="#">More</a></p>
</div>
<div style="clear:both"></div>   

<div class="red wide-full">RED CONTENTS</div>
<div class="yellow wide-full">YELLOW CONTENTS</div>
<div class="blue wide-full">BLUE CONTENTS</div>
<div class="black wide-full">BLACK CONTENTS</div>

JQuery

$('.yellow.wide-full, .blue.wide-full, .black.wide-full').hide();

$('.promo a').hover( function() {

            var parentDiv = $(this).parents().filter('.promo'),
                wideFull  = $('.wide-full');    

            switch (true) { 
                case parentDiv.hasClass('red'):
                    $('.red.wide-full').show();
                    wideFull.not('.red').hide();
                    break; 
                case parentDiv.hasClass('yellow'):
                    $('.yellow.wide-full').show();
                    wideFull.not('.yellow').hide();
                    break;                  
                case parentDiv.hasClass('blue'):
                    $('.blue.wide-full').show();
                    wideFull.not('.blue').hide();
                    break; 
                case parentDiv.hasClass('black'): 
                    $('.black.wide-full').show();
                    wideFull.not('.black').hide();
                    break;  
            }
        })

Solution

  • You can also make use of data attributes to reference corresponding divs:

    $('.wide-full:not(.red)').hide();
    
    $('.promo a').hover(function() {
        $('.wide-full').hide().filter('.' + $(this).data('type')).show();
    });
    

    http://jsfiddle.net/PyHH5/3/

    For this I modified HTML a little bit:

    <a href="#" data-type="yellow">More</a>