views:

84

answers:

3

Hi Guys,

I am learning jQuery and just came up with this - but really not sure whether it is the best solution.

Would someone be able to assist and tell me whether this is something more "elegant" ?

$('#hde_test').hide();

$('#shw_test').click(function() {
    $('#shw_test').hide();
    $('#hde_test').show();
    $('.class1').show();
});
$('#hde_test').click(function() { 
    $('#shw_test').show();
    $('#hde_test').hide();
    $('.class1').hide();
});
+2  A: 

You can use the .toggle() method or .toggleClass() method to toggle the objects visibility. That would let you do something like:

$('#show_toggle').click(function() {
    $('.class1').toggle();
});
Benjamin Manns
+5  A: 

You can shorten it down:

$('#shw_test').click(function() {
    $('#hde_test, #shw_test').toggle();
    $('.class1').show();
});
$('#hde_test').click(function() { 
    $('#hde_test, #shw_test').toggle();
    $('.class1').hide();
});

Likely, you can shorten it to:

$('#shw_test, #hde_test').click(function() {
    $('#hde_test, #shw_test, .class1').toggle();
});

Just depends how the initial state of things are.

Nick Craver
super :) thanks - just sort of thing was looking for or some sort of "toggle" - cheers.
John
oh wow didn't know there was already one there... learn something new every day!
Dave Swersky
+1  A: 

You could refactor that into a "toggle" function:

function toggle(show, hide)
{
   $(show).show();
   $(hide).hide();
}

function doStuff(){
  //this will show shw_test and hide hde_test
  toggle('#shw_test', '#hde_test');

}
Dave Swersky
jQuery has this built in :) `.toggle(true/false)`
Nick Craver
jQuery already has a .toggle function built in.
Benjamin Manns