HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

More efficient way of doing this hide()/show() jQuery

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thisshowmorewaydoingefficientjqueryhide

Problem

I currently have the following jQuery code, which does work, but I know there is a better way of doing it without having to repeat myself so much:


$(document).ready(function() {

    $('.container').hide();

    $('#btn-post').click(function() {

        $('.container').hide();

    });

    $('#btn-game').click(function() {

        $('.container').hide();
        $('#game_container').show();
    });

    $('#btn-video').click(function() {

        $('.container').hide();
        $('#video_container').show();
    });

    $('#btn-giveaway').click(function() {

        $('.container').hide();
        $('#giveaway_container').show();
    });

});


Basically, when a button is clicked, I need to show the additional div for that content type and hide the rest. If it's just a Post, then all of the divs are hidden as there is no specific div for the post type.

The HTML looks like this:


  Post
  Game
  Video
  Giveaway

game stuff

video stuff

giveaway stuff


What's the more efficient way of writing that jQuery?

Solution

Try this:

http://jsfiddle.net/VYSXn/

Change your HTML to (note the data attributes):


  Post
  Game
  Video
  Giveaway

game stuff

video stuff

giveaway stuff


and now your javascript can just be:

$(document).ready(function() {

    $('.container').hide();
    $('.btn-group button').click(function(){
        var target = "#" + $(this).data("target");
        $(".container").not(target).hide();
        $(target).show();
    });

});

Code Snippets

<div class="btn-group" data-toggle="buttons-radio">
  <button id="btn-post" class="btn btn btn-primary active" type="button">Post</button>
  <button id="btn-game" data-target="game_container" class="btn btn btn-primary" type="button">Game</button>
  <button id="btn-video" data-target="video_container" class="btn btn btn-primary" type="button">Video</button>
  <button id="btn-giveaway" data-target="giveaway_container" class="btn btn btn-primary" type="button">Giveaway</button>
</div>
<div class="container" id="game_container">
game stuff
</div>

<div class="container" id="video_container">
video stuff
</div>

<div class="container" id="giveaway_container">
giveaway stuff
</div>
$(document).ready(function() {

    $('.container').hide();
    $('.btn-group button').click(function(){
        var target = "#" + $(this).data("target");
        $(".container").not(target).hide();
        $(target).show();
    });

});

Context

StackExchange Code Review Q#13733, answer score: 7

Revisions (0)

No revisions yet.