1

Through CSS I set all divs to visibility :hidden. By clicking the item in the navbar I want the target div to be set to visibility :visible. This works just fine but I want to avoid setting it again if it is already visible.

This code doesn't work

function showNewElement(actID) {
   ID = actID.substring(1, actID.length);
   $('.mainDiv:visible').css("visibility", "hidden");
   $("#" + ID + ':hidden').css("visibility", "visible").hide().fadeIn('fast');
}

http://jsfiddle.net/dEnx5/

So I had to wrap it in an if-Statement

function showNewElement(actID) {
    var ID = actID.substring(1, actID.length);
    if ($("#" + ID).css("visibility") != "visible") {
        $('.mainDiv').css("visibility", "hidden");
        $("#" + ID).css("visibility", "visible").hide().fadeIn('fast');
    }
}

http://jsfiddle.net/qUe6k/4/

Why does it not work the other way?

3 Answers 3

2

From jQuery - :visible Selector

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

So, although you cannot see the elements, they are not in the :visible set.

What you can do instead, is using display: none on the mainDiv elements. Then it will be considered invisible

.mainDiv {
    display: none;
}

and then change the jQuery to just

function showNewElement(actID) {
    ID = actID.substring(1, actID.length);
    $('.mainDiv:visible').hide();
    $("#" + ID + ':hidden').fadeIn();
}

See modified JSFiddle

Sign up to request clarification or add additional context in comments.

Comments

0

Write:

function showNewElement(actID) {
    ID = actID.substring(1, actID.length);
    if ($("#" + ID).css("visibility") == "hidden"){
        $(".mainDiv:visible").css("visibility", "hidden");
        $("#" + ID).css("visibility", "visible");
    }
}

Fiddle here.

1 Comment

I actually wanted to get the 2-liner to work because logically it seems right but it doesn't work. I want to understand why ;)
0

It works if you change:

$("#" + ID + ':hidden').css("visibility", "visible").hide().fadeIn('fast');

To:

$("#" + ID).css("visibility", "visible").hide().fadeIn('fast');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.