JQuery toggle question

Hi all,

Im currently trying to learn JQuery and hope you can help explain my problem:

I have a paragraph that I have set to disappear on the click of the Hide button, I have also set the button to toggle between Hide and Show depending on whether or not the content is visible. My problem is, when I add ‘slow’ as the duration the button doesnt seem to toggle between hide and show?

<p id="disclaimer">
        Disclaimer! This service is not intended for the those with criminal intent. Celebrities are kind of like people so their privacy should be respected.
      </p>
$(document).ready(function() {
			$('<input type="button" class="toggle" name="toggle" value="Hide" />').insertAfter('#disclaimer');
			$('.toggle').click(function() {
				$('#disclaimer').toggle('slow');
				
				if($('#disclaimer').is(':visible')){
					$(this).val('Hide');
				}else{
					$(this).val('Show');
				}
				});
			$('<strong>START</strong>').prependTo('#disclaimer');
			$('<strong>END</strong>').appendTo('#disclaimer');
			
			
			});

It would be great if someone could explain where Im going wrong with this one, cheers!

Kyle

  1. Why are you using jQuery to insert the button into the document?

  2. Why are you checking if the paragraph is visible? Why not check what’s the value of the button you just clicked? If it’s “Hide”, by deduction you know you have to set it now to “Show”.

Hi Furicane,

Im just following along in the sitepoint novice to ninja book, and they recommend putting the button inside the jquery so that if a user has their javascript disabled then the button wont appear.

With the second point of yours again Im just following along in the book, these may be primary tips before moving onto proper methods of showing and hiding paragraphs and various other web content.

Thanks

It doesn’t work because of the .is(‘:visible’).
When .is(‘:visible’) is evaluated the div is still animating, so it’s still visible, and the button caption doesn’t change.

Try this:


$(document).ready(function() {
	$('<input type="button" class="toggle" name="toggle" value="Hide" />').insertAfter('#disclaimer');
	$('.toggle').click(function() {
		var $this=$(this);
		$('#disclaimer').toggle('slow', function() {
			$this.val( $this.val()=='Hide' ? 'Show' : 'Hide' );
		});
	});
	$('<strong>START</strong>').prependTo('#disclaimer');
	$('<strong>END</strong>').appendTo('#disclaimer');
});

:slight_smile:

Thanks for this scallio, very helpful!