jQuery show/hide/toggle works, but doesn't stay as it should - it reverts to original state

Ankur picture Ankur · Jul 16, 2009 · Viewed 10.4k times · Source

I am try to show/hide answers to FAQ questions using jQuery. The idea is that all the questions are listed and only when a user wants to see the answer they click the question (which looks like a link) and then the answer becomes visible.

It kind of works except that the answer reverts to its original state as soon as it is clicked. In this case that means when I click the question to show the answer, it shows up and then disappears in the next instant rather than staying visible till it is clicked again to toggle it to hide.

I have pasted the code below:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="jquery-1.3.2.min.js" ></script>
<script>
    $(document).ready(function() {
        $('div.showhide,#answer').hide();
        $('#question').click(function(){
        $('div.showhide,#answer').toggle();
       });
  });
</script>
</head>
<body>
<p><a href="" id="question" name="question">Question</a></p><div id="answer"     name="answer">Answer</div></p>
</body>
</html>

Answer

peirix picture peirix · Jul 16, 2009

I think there might be a problem with <a href="">... If you remove the href attribute (as it isn't needed anyway (if you want the appropriate cursor, use CSS)), it will work, at least it did for me.

As <a href=""> triggers an onClick event and refreshes the page, you can replace the blank href attribute with href="#" or href="javascript:void(0) to run the js event.