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>
jQuery hide() Method The hide() method hides the selected elements. Tip: This is similar to the CSS property display:none. Note: Hidden elements will not be displayed at all (no longer affects the layout of the page). Tip: To show hidden elements, look at the show() method.
The toggle() method toggles between hide() and show() for the selected elements. This method checks the selected elements for visibility. show() is run if an element is hidden. hide() is run if an element is visible - This creates a toggle effect.
The hide() is an inbuilt method in jQuery used to hide the selected element. Syntax: $(selector).
jQuery toggle() You can also toggle between hiding and showing an element with the toggle() method.
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.
Another way of preventing the default following behaviour of a hyperlink is to use event.preventDefault()
:
Prevents the browser from executing the default action.
I would suggest this:
$('#question').click(function(e){
e.preventDefault();
$('div.showhide,#answer').toggle()
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With