tutorials

Quintessential show/hide elements with JavaScript

Posted by on Dec 7, 2011 in tutorials | 0 comments

Add some pieces of flair

Add some pieces of flair

Even if you are making a plain old HTML page to serve as nothing more than a FAQs page you add a piece of flair to the page by using just a sprinkling of JavaScript.

Let’s say, for example, that your FAQ page largely consists of an un-ordered list of questions. Each question is hyperlinked. Within each list item, there exists a paragraph that is the answer.

Perhaps the paragraph is going to be invisible. The desired result is that when the visitor clicks on the hyperlink the paragraph becomes visible. Alternately, when the hyperlink is clicked when the paragraph is visible, the paragraph becomes hidden.

This is easy enough to achieve without any special additional libraries.

The first piece of code I’m going to post is the layout for the HTML. As I said it essentially consists of an un-ordered list with a hyperlink and a paragraph within each list item:

<ul>

 <li><a href="javascript:showAnswer('hide1')">Do you know the way to Santa Fe?</a>
   <p id="hide1" style="display: none;">Yes, head NE from Albequerque</p>
 </li>

 <li><a href="javascript:showAnswer('hide2')">What is the meaning of life?</a>
   <p id="hide2" style="display: none;">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
 </li>

</ul>

Pretty simple, eh?

As you might guess, we’re going to create a JavaScript function named showAnswer that will take an argument of the paragraph that has a specific id. Each paragraph must have a unique id in order for this to work. Additionally, make sure that each paragraph is initially set to display:none.

Now for the javaScript:

function showAnswer(which) {

 if( document.getElementById( which ) ) {
  if( document.getElementById( which ).style.display == 'none' ) {
   document.getElementById( which ).style.display = 'block';
  }
  else {
   document.getElementById( which ).style.display = 'none';
  }
 }

}

Not exceptionally verbose . . .

The script, when called, simply checks to see if, in fact, an element with the passed-in id exists. It then checks to see what the value of the CSS style “display” happens to be. If it is “none” then it will set it to “block” so the element will be visible. If it is anything other than “none” it will set the display to “none” so it is no longer visible.

If you would like to see this script working, you can see it here.

So, that’s one way of doing it right?

What if you want another way to do it using JQuery? That’s a pretty simple thing to do as well. It’s simply a matter of converting this to JQuery. Not much will have to change in your HTML.

What if you don’t want to use ids? What if you wanted to handle this with classes only? This is something I wanted to try. Here is the result. There might be a little more work to do, it was late and I was watching the movie, Unknown, at the same time:

The HTML:

<ul>

  <li><a href="#" class="showControl">Do you know the way to Santa Fe?</a>
  <p class="hid" style="display: none;">Yes, head NE from Albequerque</p>
  </li>

  <li><a href="#" class="showControl">What is the meaning of life?</a>
  <p class="hid" style="display: none;">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  </li>

  <li><a href="#" class="showControl">There is no p</a>
  <span class="hid" style="display: none;">Yes, head NE from Albequerque</span>
  </li>

</ul>

So, if you’re following along you’ll see that I removed the ids from the paragraph elements. They now have a class of “hid.” Each hyperlink element has a class of “showControl.” Notice on the third list item there is no paragraph – instead there is a span.

Here’s the JQuery:

$('.showControl').click( function(e) {
 if( $(e.target).parent().children('p.hid').length > 0 ) {
  if( $(e.target).siblings("p:first").css('display') == 'none' ) {
   $(e.target).siblings("p:first").show('slow');
  }
  else {
   $(e.target).siblings("p:first").hide('slow');
  }
 }
});

We’re doing, for the most part, the same thing we did with the previous script – with a few modifications. The script checks to see ff the parent of the target element of the event that triggered the click has any children that happen to be paragraphs. If there are, and they are hidden, it will show them. Vice-versa if the paragraphs are visible.

Also, instead of just altering the CSS style, I’m using the show or hide which throws in a little animation – extra pieces of flair.

You can see this working on this page.

However, the best way to achieve this is by not even inspecting the display attribute at all. Let jQuery handle it. There’s a handy function, slideToggle(), you can use to handle this:

$('.showControl').click( function(e) {
 if( $(e.target).parent().children('p.hid').length > 0 ) {
  $(e.target).siblings("p:first").slideToggle().animate({'backgroundColor' : '#F2DCE2'});;
 }
});

It works simply and efficiently without you having to do the extra work. For extra flair the animate function is used to highlight the paragraph. See it in action here.

I haven’t fully tested it all in a wide array of browsers. So, if you find anything, have any thoughts or comments please be sure to add to the discussion.

Read More