Omar
Omar

Reputation: 806

Fade div in and out using the same link onclick

I can fade a div in with a click but how do I use the same click to toggle that div, i.e. fade the div in on click and then fade the div out on second click.

I'd like navbar-toggle to be clicked once to open overlay and clicked again to fade out overlay.

<script>

 $(document).ready(function(e) {

  $('.navbar-toggle').click(function(e){    
    $('.overlay, .popup').fadeIn('slow');
  });

  $('.navbar-toggle').click(function(e){         
    $('.overlay, .popup').fadeIn('slow');
  });

});
</script>

Upvotes: 0

Views: 1432

Answers (3)

Ahmad Asjad
Ahmad Asjad

Reputation: 823

it also could be used like this, by checking the current status of the element

$('.navbar-toggle').click(function(e){    
    if($('.overlay, .popup').css('display')=='none')
    {
        $(".overlay, .popup").fadeIn();           
    }
    else
    {
        $(".overlay, .popup").fadeOut();            
    }
});

Or by removing curly braces due to being in single line like this

$('.navbar-toggle').click(function(e){    
    if($('.overlay, .popup').css('display')=='none')
        $(".overlay, .popup").fadeIn();   
    else
        $(".overlay, .popup").fadeOut();    
});

Check out the fiddle : JSFiddle

Upvotes: 0

imbondbaby
imbondbaby

Reputation: 6411

You can do it a couple of ways:

Solution 1:

Use toggle()

$('.navbar-toggle').click(function(e){    
    $('.overlay, .popup').toggle('fast');
});

JSFiddle Demo

Solution 2:

Use fadeToggle()

$('.navbar-toggle').click(function(e){    
    $('.overlay, .popup').fadeToggle(300);
});

JSFiddle Demo

Solution 3:

Have a hidden class and check to see if it exists

Upvotes: 2

Kevin Boucher
Kevin Boucher

Reputation: 16675

Just use toggle and bind your element to one event handler:

$('.navbar-toggle').click(function(e){    
    $('.overlay, .popup').toggle('slow');
});

Upvotes: 0

Related Questions