H. Ferrence
H. Ferrence

Reputation: 8116

How to Show Hidden Content Block via jQuery

I have the following html:

<div class="contentBlock">
  <div><img src="images/help.png" alt="help button" class="helpButton"></div>
  <div class="helpBlock">
    <p>...some hidden text...</p>
  </div> <!-- end .helpBlock -->
  <h2>A Header</h2>
  <p>...some visible text...</p>
</div> <!-- end .contentBlock -->

I have the following css:

div.contentBlock {
  position: relative; /* required for z-index */
  z-index: 1; /* interacts with div.helpBlock */
}
div.helpBlock {
  display: none;
  position: relative; /* required for z-index */
  z-index: 10; /* interacts with div.contentBlock */
}

I have the following jQuery:

$(document).ready(function() {
  // Show helpBlock on page
  $('img.helpButton').click(function(){
    /*$(this).closest('.helpBlock').show();*/ // does not work
    /*$(this).closest('.helpBlock').css('display');*/ // does not work
    var $contentWrapper = $(this).closest('.helpBlock');
    var $siblings = $contentWrapper.siblings('.helpBlock');
    $siblings.find('.helpBlock').show(); // does not work
  });
  // end Show helpBlock
}) // end jQuery Functions

I am trying to get the .helpBlock to display when I click the help button but none of my jquery is working.

Can anyone assist?

THanks.

Upvotes: 0

Views: 440

Answers (2)

Jai
Jai

Reputation: 74738

Try this one:

$('img.helpButton').click(function(){
   var $contentWrapper = $(this).parent();
   var $siblings = $contentWrapper.siblings('.helpBlock');
   $siblings.show();
});

if you want a one liner:

$('img.helpButton').click(function(){
   $(this).parent().siblings('.helpBlock').show();
});

Upvotes: 1

PlantTheIdea
PlantTheIdea

Reputation: 16369

Because your button is encased in a DIV, it will not use .closest() or .find(). You are already clicking on the button, you can use $(this) and navigate from there with .parent() and then .next():

$(this).parent().next('.helpBlock').show();

That should work. This should also eliminate the unnecessary variables:

var $contentWrapper = $(this).closest('.helpBlock');
var $siblings = $contentWrapper.siblings('.helpBlock');

Upvotes: 4

Related Questions