jQuery visible

17.Nov.2010

Use jQuery visible selector to check if element is visible, and make a menu. To use jQuery visible selector and check if element is visible, just use following snippet.

1
2
3
4
5
if(jQuery('#your-jquery-visible-id').is(':visible')) {
	alert('jQuery says: "It is visible!"');
} else {
	alert('jQuery says: "It is not visible."');
}

Now that we know how to use jQuery to check if element is visible – we can build simple menu. The first part would be HTML.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<ul id="nav-jquery-visible">
	<li>
		<a href="javascript:void(0);" onclick="toggleSubmenu(this)">Music</a>
		<ul>
			<li><a href="http://shufflable.com/en/play/music/rock">Rock</a></li>
			<li><a href="http://shufflable.com/en/play/music/pop">Pop</a></li>
			<li><a href="http://shufflable.com/en/play/music/hard+rock">Hard rock</a></li>
			<li><a href="http://shufflable.com/en/play/music/blues">Blues</a></li>
			<li><a href="http://shufflable.com/en/play/music/metal">Heavy metal</a></li>
		</ul>
	</li>
	<li>
		<a href="javascript:void(0);" onclick="toggleSubmenu(this)">Programming</a>
		<ul>
			<li>PHP</li>
			<li>JavaScript</li>
			<li>Ruby</li>
			<li>C</li>
			<li>Java</li>
		</ul>
	</li>
</ul>

Than we make sure in CSS that submenu is not visible.

#nav-jquery-visible ul {
	display: none;
}

Finaly, we make JavaScript to put jQuery visible in use.

1
2
3
4
5
6
7
8
9
function toggleSubmenu(element) {
	var child = jQuery(element).parent().filter(':first').children('ul');
 
	if(jQuery(child[0]).is(':visible')) {
		jQuery(child[0]).slideUp();
	} else {
		jQuery(child[0]).slideDown();
	}
}

Using jQuery visible in example