1

I want to make in if...else statement in jQuery but I am not sure how to set it up for what I want.
Here is what I have:

$(document).ready(function(){
  $("#quotes").hide();
  $("button").click(function(){
    if($("#quotes").hide()==true){
      $("#summary").hide();
      $("#quotes").fadeIn("slow");
    } else {
      $("#quotes").hide();
      $("#summary").fadeIn("slow");
    }
  });
});

I want it so that if #quotes is hidden, then on button click, hide #summary and fadeIn #quotes. Otherwise, (if #quotes is showing) hide #quotes and fadeIn #summary.

1
  • 1
    use $('#quotes').toggle() Commented Mar 4, 2013 at 7:06

3 Answers 3

4

You can pass the :visible selector to the is() method:

$("button").click(function() {
    if(!$("#quotes").is(":visible")) {
        $("#summary").hide();
        $("#quotes").fadeIn("slow");
    } else {
        $("#quotes").hide();
        $("#summary").fadeIn("slow");
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

What does the ! do in if(!$("#quotes")
@TheWalkingPacifist, it negates the return value of is(). Therefore, the conditional expression will be true if the element is hidden and false if it is visible. You could also use the :hidden selector and remove the !, as Sudip Pal does in his answer.
Thank you. Your answer and explanation is much appreciated and worked perfectly.
1

You should change the if checking like this,

 if($("#quotes").is(':hidden')==true){

Comments

0

Consider the following code

 $("#quotes").hide();
 $("button").click(function(){
    $("#summary").slideToggle();
    $("#quotes").slideToggle();
 });

2 Comments

Why downvote? What is the reason of making condition if there is function in jquery doing exactly this.
I did not downvote, but two calls to slideToggle() are not the same as one call to show()/hide() followed by one call to fadeIn()/fadeOut() with a slow duration. This code also assumes the two elements are in the appropriate initial conditions (#summary visible and #quotes hidden).

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.