user2564649
user2564649

Reputation: 65

Jquery: fadeOut happens immediately after fadeIn

I've got two elements (one is button) and would like to make that when I press button another element would fade in and stay. And only when I press button again, it would fade out. Now what I've got is that it does fade out automatically before I press the button again. What kind of "stop" do I need to use? Thanks.

Jquery:

$(document).ready(function(){ 
  $("#first").click(function() { 
    $("#box").fadeIn("slow");
  });

  $("#first").click(function() { 
    $("#box").fadeOut("slow"); 
  });
}); 

Upvotes: 0

Views: 364

Answers (3)

MonkeyZeus
MonkeyZeus

Reputation: 20747

I would try something like:

$(document).ready(function(){ 
  $("#first").on('click', (function() {
    //check #box visibility state
    if($('#box').is(':visible')){
        $('#box').fadeOut('slow');
    }
    else{
        $('#box').fadeIn("slow");
    }
});

Upvotes: 0

Shomz
Shomz

Reputation: 37711

You can also specify the button state... This will work for all kinds of functions, even those that don't have the toggle version of them (like fadeToggle). Like this:

var buttonFaded = false;
$(document).ready(function(){ 
    $("#first").click(function() { 
        if (buttonFaded) {
            $("#box").fadeIn("slow");
            buttonFaded = true; // even better to put this inside the fadeIn callback
        else {
            $("#box").fadeOut("slow");
            buttonFaded = false;
        }
    });
}); 

EDIT

If you just need the most basic usage, @fsw's example will work perfectly. However, if you need any customizations/more complex usages, you'd have to do something like this.

p.s. greetings to the downvoter - hopefully you'll understand some day

Upvotes: 0

fsw
fsw

Reputation: 3695

$(document).ready(function(){ 
  $("#first").click(function() { 
    $("#box").fadeToggle("slow");
  });
}); 

click adds function to stack of functions that are happening when event occurs. in your code you are doing both things at once when user clicks the element.

Upvotes: 4

Related Questions