How to reduce this jQuery load?

I am very good at jQuery, but when I like it, 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 I don’t need to basically continue to call the same thing for every other instance.

Any help at all is great! Even just telling me that this is impossible! :-)

+3
source share
2 answers
// 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;
})
+9
source

Try this using 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 light as possible, as it connects several 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;
});
+1
source

Source: https://habr.com/ru/post/1733192/


All Articles