Konrad Viltersten
Konrad Viltersten

Reputation: 39182

How to toggle jQuery element with a duration AND display?

When I want to toggle off a component I can use

$("#donkey").toggle(false);

and when I need it to be toggled during a certain time period I can use

$("#emailInvalid").toggle(700);

but now I'd like to combine those two. I want to ensure that the component is being toggled off (not only toggled back and forth) and I want to specify a duration of the process.

According to the jQuery API, I'm supposed to be able to specify an object with options, too. However, the following

$("#donkey").toggle({ duration: 700, display: false });

only toggles the donkey back and forth (during said time, though), whereas I'd like it to be toggled to invisibility. When I reviewed the options, I noticed that there's none that addresses display, so I fear that the above is treated by jQuery equivalently with

$("#donkey").toggle({ duration: 700, biteMe: "in the donkey" });

How can I make sure that the toggler is hiding the component (equivalent with the first line of code above) and that I can control the time for the process to be done (equivalent to the second line of code above)?

Upvotes: 4

Views: 3925

Answers (4)

hoefsten
hoefsten

Reputation: 1

This small plugin would allow you to combine the two:

(function ( $ ) {
  $.fn.myToggle = function(show, options) {
    return this.each(function() {
      if ($(this).is(":hidden") ? show : !show) $(this).toggle(options);
    });
  };
}( jQuery ));

Simple example:

$("#donkey").myToggle(false, 700);

Upvotes: 0

user1675891
user1675891

Reputation:

Short answer - you can't.

Your options are to build something custom and carry out the logic in custom code. Alernatively, you might want to toggle between differen classes that have the look that you like. Check out toggleAss() for details.

For completeness I also give you a link to animate() as suggested by @DavidThomas, although I haven't used that one very much.

Upvotes: 0

rishabh dev
rishabh dev

Reputation: 1743

Apply toggle only when visible:

 $('#donkey:visible').toggle(500);

Alternatively

   var element=$('#donkey');  
    if(element.css('display') !== 'none'){ 
    element.toggle(500);
}

Upvotes: 2

Steve Clason
Steve Clason

Reputation: 301

I think this is what you want -- if the element (#donkey) is visible it gets hidden, if it's hidden nothing happens.

$( '#button' ).click( function(){
  if( $( '#donkey' ).css( 'display' ) === 'block' ) {
    $("#donkey").toggle( 700 );
  }
});

Codepen: http://s.codepen.io/SteveClason/debug/RRwpBd

Upvotes: 0

Related Questions