in General

Simple jQuery example

This is a very simple jQuery example which shows a HTML defintion list being hidden and shown when clicking on a parent branch.

Although this is a very basic example of jQuery in action, it does show the ability to separate Javascript actions and your HTML.

This code assumes you have the jQuery library in the same folder as your html.

You can also find an alternative Defintion list menu action on this demo page, as well as this screencast.

Code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>jQuery | Example</title>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta http-equiv="Content-Language" content="en-gb" />
    <meta http-equiv="pragma" content="no-cache" />
    <meta http-equiv="expires" content="-1" />
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">

      // is document ready?
      $(document).ready(function() {

                // hide all DD automatically
		$('#faq').find('dd').hide();
		
                // if dt clicked then slide up or down.
		$('#faq').find('dt').click(function() {
			   answer = $(this).next();

			 if (answer.is(':visible')) {
				 answer.slideUp();
			 } else {
				 answer.slideDown();
			 };
		 });

	});

    </script>

    <style type="text/css">

		dt {
			cursor:pointer;
		}
		dt:hover {
			border:1px solid red;
		}
    </style>
</head>

<body>

<div id="faq">
	<h1>FAQ</h1>

	<dl>

	  <dt>block-level elements</dt>
	  <dd>
		<p>
		  in html, block-level elements may generally contain
		  inline elements and other block-level elements. they are
		  usually formatted differently than inline elements,
		  typically on a new line in visual browsers.
		</p>
	  </dd>

	  <dt>inline elements</dt>
	  <dt>text-level elements</dt>
	  <dd>
		<p>
		  inline (or text-level) elements generally only contain
		  character data and other inline elements.
		</p>
	  </dd>

	</dl>


	<dl>
		<dt>Coffee</dt>
		<dd>Black hot drink</dd>
		<dt>Milk</dt>
		<dd>White cold drink</dd>
	</dl>
</div>

</body>
</html>