RegexCommander
RegexCommander

Reputation: 23

yet another "toggle visibility" question

I am stuck with the following code:

http://jsfiddle.net/2v4aJ/

I want to toggle some text using hidden/visible.

I am using javascript functions to add dynamic text to the page, that's why I use .live ...

I can toggle to hide, but not to visible (if($('#1').is(':hidden')) is never true).

Any help appreciated :-)

Upvotes: 2

Views: 168

Answers (4)

Samich
Samich

Reputation: 30185

First of all :hidden selector is not for you:

Elements with visibility: hidden or opacity: 0 are considered to be visible, since they still consume space in the layout.

You can use :visible selector, but it works only when element invisible and display:none. In your case you need to check css property:

Also, pleae note that visibility:hidden reserves space for element, display:none - not;

If you don't need to reserve space for it I suggest to use:

        $('#text').click(function() {
            $('#2').toggle();
        });  

Code: http://jsfiddle.net/2v4aJ/6/

Upvotes: 0

Einacio
Einacio

Reputation: 3532

according to the jQuery docs on :hidden,

Elements with visibility: hidden are considered to be visible, since they still consume space in the layout

so you'd better check for the value.

if ($('#1').css('visibility')==='hidden')

or use other method

Upvotes: 1

mlathe
mlathe

Reputation: 2385

use the toggle command.

$('#1').toggle(true); //show
$('#1').toggle(false); //hide
$('#1').toggle(); //flip

Upvotes: 0

James Allardice
James Allardice

Reputation: 166071

The problem is that the :hidden pseudo-selector treats elements with visibility:hidden as visible, because they still take up space on the page. From the jQuery docs:

Elements with visibility: hidden or opacity: 0 are considered to be visible, since they still consume space in the layout.

Instead, you can check the value of the CSS property itself:

if($('#1').css("visibility") === "hidden") {
    $('#1').css('visibility','visible');
}
else {
    $('#1').css('visibility','hidden');
}

Upvotes: 1

Related Questions