Javascript to show/hide dt when dd clicked

Hi,
I’m fairly new to Javascript, and am trying to create a list of questions and answers, with the questions hidden on page load.
They get hidden by this Javascript (to avoid breaking the site for those without JS):

function init() {
	var dds = document.getElementById("qanda").getElementsByTagName("dd");
	for (var ddid=0; ddid<dds.length; ddid++){
		dds[ddid].style.display = 'none';
	}
}

My HTML is:

<dl id="contact-qanda">
      <dt onclick='showme()'>Q: How do I sell on this site?</dt>
        <dd>A: You don't! This is a search tool to help buyers find underpriced bargains. It doesn't directly accept listings.</dd>
      <dt onclick='showme()'>Q: How do I join?</dt>
        <dd>A: You don't! There is no need to join our site to use it!<br>You might want to sign up with eBay, which can be done at <link>.</dd>

Can anyone give me any pointers on how I can go about displaying the <dd> tags again? I’ve tried Google, but not being familiar with Javascript terminology, haven’t got very far!

Thanks in advance,

BayCrazy

What you are looking for is usually called a “toggle”, where, in your example, you click on the <dt> and it ‘toggles’ the view of the corresponding <dd>.

Using plain Javascript, I use this:


<!DOCTYPE html>
<html>
	<body>
		<dl id="contact-qanda">
			<dt class="toggle">Q: How do I sell on this site?</dt>
			<dd>A: You don't! This is a search tool to help buyers find underpriced bargains. It doesn't directly accept listings.</dd>
			<dt class="toggle">Q: How do I join?</dt>
			<dd>A: You don't! There is no need to join our site to use it!<br>You might want to sign up with eBay, which can be done at <a href="#">link</a>.</dd>
		</dl>
		<script>
			// Source: Sitepoint book "Simply Javascript"
			// Modified for use with the document object
			document.getElementByClass = function(theClass) {
				var elementArray = [];
				if (typeof document.all != "undefined") {
					elementArray = document.all;
				} else {
					elementArray = document.getElementsByTagName("*");
				}
				var matchedArray = [];
				var pattern = new RegExp("(^| )" + theClass + "( |$)");
				for (var i = 0; i < elementArray.length; i++) {
					if (pattern.test(elementArray[i].className)) {
						matchedArray[matchedArray.length] = elementArray[i];
					}
				}
				return matchedArray;
			};	
			// Toggle Functions
			// Source modified from http://bonrouge.com/~togglit
			function toggleNext(elm) {
				var next = elm.nextSibling;
				while ( next.nodeType !== 1 ) {
					next = next.nextSibling;
				}
				next.style.display = (
					(next.style.display === "none")
						? "block"
						: "none"
				);
			}

			function toggleEl(elm) {
				elm.className += ' ' + 'clicker';
				elm.onclick = function() {
					toggleNext(this);
				}
				toggleNext(elm);
			}

			var sheet = document.createElement('style');
				sheet.innerHTML = ".clicker { cursor: pointer; color: blue; text-decoration: underline;}";
				document.head.appendChild(sheet);
			var toggle = document.getElementByClass("toggle");
			if ( toggle != undefined ) {
				for (var i in toggle) {
					toggleEl( toggle[i] );
				}
			}			
		</script>
	</body>
</html>

If you are using a framework like jQuery, you can do this:


<!DOCTYPE html>
<html>
	<body>
		<dl id="contact-qanda">
			<dt>Q: How do I sell on this site?</dt>
			<dd>A: You don't! This is a search tool to help buyers find underpriced bargains. It doesn't directly accept listings.</dd>
			<dt>Q: How do I join?</dt>
			<dd>A: You don't! There is no need to join our site to use it!<br>You might want to sign up with eBay, which can be done at <a href="#">link</a>.</dd>
		</dl>
		<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
		<script>
			$('#contact-qanda dt').each(function() {
				$(this).next().hide();
			});		
			$('#contact-qanda dt').click(function() {
				$(this).next().toggle();
			});
		</script>
	</body>
</html>

I don’t see how your init() function will work in javascript disabled browsers :confused:.

In any case, this code uses css to hide the answers on page load and javascript to toggle the display/hiding of the clicked question’s answer.

        
       <style type="text/css">
            #contact-qanda dd {
                display: none;
            }
            #contact-qanda dt:hover {
                cursor: pointer;
            }
        </style>

        <dl id="contact-qanda">
            <dt class="dtQuestions">Q: How do I sell on this site?</dt>
            <dd>A: You don't! This is a search tool to help buyers find underpriced bargains. It doesn't directly accept listings.</dd>
            <dt class="dtQuestions">Q: How do I join?</dt>
            <dd>A: You don't! There is no need to join our site to use it! <br /> You might want to sign up with eBay, which can be done at <a href="#">link</a>.</dd>
        </dl>


        <script type="text/javascript">
            function showHideAns(obj){
                //get dd for this dt
                var ddO = obj.nextSibling;
                while(ddO.nodeName.toLowerCase() != 'dd'){
                    ddO = ddO.nextSibling;
                }
                //toggle the display status of the dd
                ddO.style.display = (ddO.style.display == 'block')? 'none' : 'block';
            }
            var dtQuestionO = document.getElementsByClassName('dtQuestions');
            for(i=0; i < dtQuestionO.length; i++){
                dtQuestionO[i].onclick = function(){
                    showHideAns(this);
                }
            }
        </script>

The js needs to be below the html, preferable just above the </body>.

@webdev - by using CSS to hide the <dd>'s, those with JS turned off will never see that contact

the op can then use their existing init() function to hide the dd’s.