robdodson
robdodson

Reputation: 6786

jQuery: Is there a better way to switch two divs?

I'm currently using the following block of code to switch between two divs.

$('.btn-my-projects').click(function(e) {
    $('.my-projects').show();
    $('.all-projects').hide();
});

$('.btn-all-projects').click(function(e) {
    $('.my-projects').hide();
    $('.all-projects').show();
});

Obviously it works but I'm wondering if there's a better way to do this. Feels like it could be compressed down to one handler vs. two. If I use delegation I can make it a single handler but it will become longer, requiring a conditional check to see which button was clicked.

Upvotes: 1

Views: 198

Answers (4)

John Vinyard
John Vinyard

Reputation: 13485

What about using custom attributes?

Html:

<div class='my-projects'>my-projects</div>
<div class='all-projects'>all-projects</div>
<span class='toggler' hide='.all-projects' show='.my-projects'>btn-my-projects</span>
<span class='toggler' hide='.my-projects' show='.all-projects'>btn-all-projects</span>

and Javascript:

$('.toggler').click(function(e) {
    $($(this).attr('hide')).hide();
    $($(this).attr('show')).show();
});

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359826

Simple:

function toggle(all) {
    $('.all-projects').toggle(all);
    $('.my-projects').toggle(!all);
}

$('.btn-my-projects').click(function() {
    toggle(false);
});

$('.btn-all-projects').click(function() {
    toggle(true);
});

If you want to get more terse:

function makeClickHandler(all) {
    return function () {
        $('.all-projects').toggle(all);
        $('.my-projects').toggle(!all);
    };
}

$('.btn-my-projects').click(makeClickHandler(false));
$('.btn-all-projects').click(makeClickHandler(true));

Alternately, you could take a completely different approach and put the link between which button shows & hides which div into the markup, using an HTML5 data-* attribute. Something like this:

<button class="project-control" data-show=".all-projects">
    Show all projects
</button>
<button class="project-control" data-show=".my-projects">
    Show my projects
</button>

<div class="project all-projects">...</div>
<div class="project my-projects">...</div>

with JavaScript like this:

$('.project-control').on('click', function () {
    var showSelector = $(this).data('show');
    $('.project').hide();
    $(showSelector).show();
});

N.B. in a real page, you would probably want to cache the selected elements.

Upvotes: 4

user827080
user827080

Reputation:

You could use toggle() instead of show() and hide(). Then you could add a class .projects to the .my-projects and .all-projects divs and just toggle that selector.

Upvotes: 1

mr_lewjam
mr_lewjam

Reputation: 1190

The method that you are using is the way I would do it, but if you want to condense, may jquery's toggle would be of use to you http://api.jquery.com/toggle/

Upvotes: 0

Related Questions