0

Trying to solve this problem:

I have the following set of divs that when clicked show a particular panel. I can do this by hard coding the values, but was wondering how to go about this in the most efficient way.

<div id="myContainer">
<div id="myMenu_1" class="myMenu">Menu1</div>
<div id="myMenu_2" class="myMenu">Menu2</div>
<div id="myMenu_3" class="myMenu">Menu3</div>
</div>

<div id="myPanel_1" class="myPanel">If Menu1 is clicked show this panel</div>
<div id="myPanel_2" class="myPanel">If Menu2 is clicked show this panel</div>
<div id="myPanel_3" class="myPanel">If Menu3 is clicked show this panel</div>

As noted above, I know how to do this by

$('myMenu_1').click(function(){$('myPanel_3').hide();$('myPanel_2').hide();$('myPanel_1').show();});

But this doesn't seem very efficient if I have to do it for multiple items.

3 Answers 3

3

This will work with an arbitrary number of <div>s:

$("div.myMenu").click(function() {
  $("div.myPanel").hide();
  var index = $(this).attr("id").split("_")[1];
  $("div#myPanel_" + index).show();
});
Sign up to request clarification or add additional context in comments.

3 Comments

ah yes, that makes sense... will accept in 8 min. thanks paul!
Paul, any idea why this wouldn't show the panel until the second click? Having issues here :(
Please link to the page with the problem.
1

You can hide all of them with prefix selector, and then show only the required one. that would make your code simpler and shorter.

Something like this, forgive any errors, I did not test this, and I am not fluent in jQuery.

   $('[id$=foo]')
    $('[^id=myMenu').click(
    function(){ $([^id=myPanel).hide(); // hide all panels 
                 var toShowId = $(this).attr('id').replace("myMenu","myPanel");
                 $('#'+toShowId).show(); // show corresponding panel .
     }
    );

Comments

0
$('myMenu_1').click(function() { 
    $("div[id^='myPanel_']").hide(); 
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.