15

I was wondering if toggle() and fadeIn() could be used in one function...

i got this to work, but it only fades in after the second click... not on first click of the toggle.

$(document).ready(function() {

 $('#business-blue').hide();

  $('a#biz-blue').click(function() {
    $('#business-blue').toggle().fadeIn('slow');
    return false;
  });

// hides the slickbox on clicking the noted link 

  $('a#biz-blue-hide').click(function() { 
     $('#business-blue').hide('fast'); 
     return false; 
  }); 


});



  <a href="#" id="biz-blue">Learn More</a>
        <div id="business-blue" style="border:1px soild #00ff00; background:#c6c1b8; height:600px; width:600px; margin:0 auto; position:relative;">
            <p>stuff here</p>
        </div>
tony noriega
  • 7,523
  • 17
  • 53
  • 72

6 Answers6

22

Since jQuery 1.4.4 there is a new function for this called .fadeToggle()

Jquery fadeToggle

Pete
  • 57,112
  • 28
  • 117
  • 166
Konstantine Kalbazov
  • 2,643
  • 26
  • 29
13

You can use toggle() to alternate between a set of functions. So if you want an element to fadeIn and fadeOut every other click, have a toggle control 2 functions: the fadeIn and the fadeOut. Like this:

$('a#biz-blue').toggle(function() {
    $('#business-blue').fadeIn('slow');
    return false;
  },
function() {
    $('#business-blue').fadeOut('slow');
    return false;
  });
pixeline
  • 17,669
  • 12
  • 84
  • 109
  • 2
    Note that this method signature has been removed from jQuery as of 1.9: http://jquery.com/upgrade-guide/1.9/#toggle-function-function-removed – Zhihao Dec 17 '14 at 22:42
4

Your question confuses me a bit, because .toggle() is basically a show/hide toggle, but you have fadeIn. The closest guess I have is that you want a fade-toggle, in which case you can do this using animate():

$('#business-blue').animate({opacity: 'toggle'}, 800); 

Another option you may want is the slide up and down using .slideToggle() like this:

$('#business-blue').slideToggle('slow');
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
1

Much better to write a custom function at the bottom of jquery.js:

jQuery.fn.fadeToggle = function(speed, easing, callback) {
   return this.animate({opacity: 'toggle'}, speed, easing, callback);
};

Then you can call it like this:

$('#hiddenElement').fadeToggle('fast');
cronoklee
  • 6,482
  • 9
  • 52
  • 80
0

Very simple

$("a#biz-blue").live('click',function(){
   $('#business-blue').slideToggle(200);
});
Fawad Ghafoor
  • 6,039
  • 7
  • 41
  • 53
0

It also looks like someone wrote a plugin for this two years ago.

Roman
  • 19,581
  • 6
  • 68
  • 84