Monday, January 14, 2013

Toggle Your Content in a Snap!

A common conundrum for web designers is how to make a lot of content easily accessible for their viewing audience. It’s difficult to navigate through a really long page with a bunch of jump links.

Here’s a clean and easy way to neatly organize your content so that it’s easy to navigate. We use the toggle method throughout the AYSO National website. If you’ve ever looked at one of the FAQ pages or the new Section Meeting microsite, I’m sure you’ve seen it!

jQuery Toggle Method

Let's use a FAQ example. You have a question with an associated answer. We only want to show the answer when you click on the question. With this method, clicking a second time on the question will hide the answer.
QUESTION: Where is the soccer field?

ANSWER: Down the street and around the corner.




First, we’ll wrap the question in a labeled tag:

<div id="question1">QUESTION: Where is the soccer field?</div>

Next, we’ll wrap the answer in a labeled tag and set it to hide:

<div id="answer1">ANSWER: Down the street and around the corner.</div>

Now we put the appropriate script in the header tag:


<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){   
 $('#question1).click(function(){     
  $('#answer1').toggle('slow');   
 }); 
});
</script>
</head>


And give it some style (in the header tag as well):


<style>
#question1 {display: block; cursor: pointer; text-decoration: underline;}
#answer1 {display: none;}
</style>


That’s it! You should have a working toggle for your page! Try it out here.


Here’s the full code for the HTML page:

<!DOCTYPE html>
<html>
<head>
<style> #question1 {
 display: block;
 cursor: pointer;}
#answer1 {display: none;}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
$(document).ready(function(){   
 $('#question1').click(function(){     
  $('#answer1’).toggle(300);   
 }); 
});

</script>
</head>
<body>

<div id="question1">QUESTION: Where is the soccer field?</div>

<div id="answer1">ANSWER: Down the street and around the corner.</div>

</body>
</html>

No comments:

Post a Comment