tags:

views:

73

answers:

4

Hi all, In a jquery code, I am dynamically showing and hiding some content.

            if (this.hide()) {

                this.show();
                                }
            else {
                alert("Hello");
                this.hide();

            }

But else part is never getting executed.why?

+3  A: 

I'd do something like this :

if($(this).is(':hidden')) { 
    $(this).show();
}
else {
  $(this).hide();
}

Or depending on what you want to do, you can try toggle()

Soufiane Hassou
I'd go for the toggle option in most cases.
Kezzer
A: 

In the if you are hidding the element. You should do this.is(':hidden')

Daniel Moura
+1  A: 

What you're looking for is

this.toggle();

The reason you never reach your 'else' clause is because hide() returns the elements found in the selector (for method chaining reasons). Since it always returns a valid object, it will always resolve to "truthy", i.e. not null, "", 0, false, etc.

David Hedlund
A: 

this.hide() is running the hide function, not checking if it's hidden, thus it's setting it to hide and then running this.show()

as already said toggle() is what you want as it does the check for you without having to code for that.

andy-score