2

There are button (id= "hide_message_button") and message(id="message"). The click on the button should hide/show the message. The source code:

$('#hide_message_button').click(function(){ var bool = $('#message').css('visibility','hidden').is(':hidden'); if(bool){ $('#message').show(); $(this).val('Hide'); } else { $('#message').hide(); $(this).val('Show'); } }); 

I have a bug: the message is hidden with first click on the button and didn't shown again (but button's value is changed to 'Show'). What's wrong? Thanks.

5 Answers 5

3

Try:

$('#hide_message_button').click(function(){ $('#message').toggle(); }); 
Sign up to request clarification or add additional context in comments.

Comments

2

Elements with visibility: hidden style properties are not hidden, since they occupy space in layout. Try:

var bool = $('#message').is(":hidden"); 

or:

var bool = $('#message:hidden').length; 

or:

var bool = $('#message').css("display") == "none"; 

From the manual:

Elements can be considered hidden for several reasons:

  • They have a CSS display value of none.
  • They are form elements with type="hidden".
  • Their width and height are explicitly set to 0.
  • An ancestor element is hidden, so the element is not shown on the page.

1 Comment

thanks! I tried all three options and all three ones work absolutely right. It is very interesting solution with "length".
2

That's because the css('visibility','hidden') call is hiding the message, and then it's never shown again because the show method doesn't change the visibility style.

The element will then toggle between being hidden (display=block, visibility=hidden) and being removed (display=none, visibility=hidden). In one state the element takes up space, but the message is not shown in either state.

Just remove the code that sets the visibility style, and the code works.

Demo: http://jsfiddle.net/Guffa/JqE3Y/

3 Comments

I think that the bool has also true value because the button's value changes with each click from "Show" to "Hide" and viceversa. I also tested it with alert message that I put in the "if" block.
@tatiana_c: Yes, it does, actually. I already updated my answer with a more accurate description, and a corrected code.
Thank you very much for the demo and the answer. It works and it's great.
1

Use toggle instead of verify visibility. This code works: http://jsfiddle.net/8qu9y/

Comments

0

Take a look at the toggle function.

<input type="button" id="hide_message_button" value="My button" /> <p id="message">A message</p>​ 

and

$('#hide_message_button').click(function(){ $('#message').toggle(); });​ 

2 Comments

I don't see why the button also disappear if you just toggled the #message id...
Yes, you are right. I wrote before something different. This code works fine. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.