We help IT Professionals succeed at work.

JQuery - Toggle

Medium Priority
554 Views
Last Modified: 2012-03-13
Dear Experts,

In the attached small code I am just trying the JQuery bases, could you please advise how a condition could be put to it?

I would like that the <h2> element would be toggled only, if its node value is "This is also a h2 element", so only the second one.

thanks,

<html>                                                                 
<head>                                                                 
	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>       
	<script type="text/javascript">                                       
		$(document).ready(function() {
			$("h1").click(function() {
				$('h2').slideToggle();
			});
		});                                 
	</script>                                                             
</head>                                                               
<body>                                                                 
<h1>Click to here to hide the h2 element</h1>
<h2>This is a h2 element</h2>
<h2>This is also a h2 element</h2>                                  
</body>                                                               
</html>

Open in new window

Comment
Watch Question

$(document).ready(function() {
			$("h1").click(function() {
				$('h2').eq(1).slideToggle();
			});
		});    

Open in new window

csehzIT consultant

Author

Commented:
Thanks the solution, is it possible to make it also with using IF?

Basically I would like to see an example how a condition could be put. So around if "IF node value is something, then do toggle"
...or

$(this).next().slideToggle();

...in your click handler
you mean this;

	$(document).ready(function() {
			$("h1").click(function() {
			alert($('h2').eq(1).text())
			   if($('h2').eq(1).text() == 'This is also a h2 element')
				$('h2').eq(1).slideToggle();
			});
		});

Open in new window

csehzIT consultant

Author

Commented:
Yes exactly thanks very much

Explore More ContentExplore courses, solutions, and other research materials related to this topic.