views:

86

answers:

2

I'm pretty good with jQuery but when I get to stuff like this I need a little help.

So I want to shorten this code:

$(function() {
$('#experience_nav').click(function() {
    $('#contentWrap').load('files.html #content_experience', function() {
        $(this).hide().fadeIn();
        $('#content_experience').siblings().fadeOut();
    });

    return false;
});
$('#aboutme_nav').click(function() {
    $('#contentWrap').load('files.html #content_aboutme', function() {
        $(this).hide().fadeIn();
        $('#content_aboutme').siblings().fadeOut();
    });

    return false;
});
$('#recentclients_nav').click(function() {
    $('#contentWrap').load('files.html #content_recentclients', function() {
        $(this).hide().fadeIn();
        $('#content_recentclients').siblings().fadeOut();
    });

    return false;
});
$('#contactme_nav').click(function() {
    $('#contentWrap').load('files.html #content_contactme', function() {
        $(this).hide().fadeIn();
        $('#content_contactme').siblings().fadeOut();
    });

    return false;
});

});

So that I don't have to basically keep calling the same thing for each different instance.

Any Help at all is great! Even just telling me it can't be done! :-)

+9  A: 
// All <a>s wich the ID ends with '_nav'
$('a[id$="_nav"]').click(function() {
    var nav = $(this).attr('id').replace('_nav', '');

    $('#contentWrap').load('files.html #content_' + nav, function() {
        $(this).hide().fadeIn();
        $('#content_' + nav).siblings().fadeOut();
    });

    return false;
})
TiuTalk
Thanks! Works Perfectly. Awesome! :-)
KayRoseDesign
To make it more lightweight in this case: `$('a[id$="_nav"]').live('click',function(){`....
Nick Craver
@Nick Craver - If you don't need to use the live() why use the live()?
TiuTalk
@TiuTalk - Live listens at a higher level (DOM root) rather than analyzing every element and hooking up duplicates of the same event handler, it's recommended when using the same event handler multiple times.
Nick Craver
+1  A: 

Try this, taking advantage of your naming scheme:

$('#experience_nav, #aboutme_nav, #recentclients_nav, #contactme_nav').click(function() {
    var id = '#content_' + $(this).attr('id').replace("_nav","");
    $('#contentWrap').load('files.html ' + id, function() {
        $(this).hide().fadeIn();
        $(id).siblings().fadeOut();
    });
    return false;
});

Alternatively, as lightweight as possible since it's hooked up multiple times:

$('[id$=_nav]').live('click', function() {
    var id = '#content_' + $(this).attr('id').replace("_nav","");
    $('#contentWrap').load('files.html ' + id, function() {
        $(this).hide().fadeIn();
        $(id).siblings().fadeOut();
    });
    return false;
});
Nick Craver
This works perfectly aswell. Thanks both of you :-)
KayRoseDesign