March 11, 2013

How To Write A Simple Click Opacity Fade?

Question by user2122160

Okay, so I’m simply trying to make the opacity fade from 0 to 1 and then 1 to 0 on click. I’m assuming that I need to write an if statement. Here is the code as it is right now.

$(document).ready(function() {
     $('#soilink').click(function() {$('#soi').animate({opacity:1}, 400 );}

    );

So right now, if I click on the link on my website, the div area called #soi fades in. However, the second part is that I need to be able to click the link once again so it fades back to 0. Haven’t quite figured that part out.

EDIT

I want this to toggle, however using the toggle function will result in the div completely becoming absent from the html, causing other divs to shift.

Answer by Starx

There is a fadeTo() function for that

$('#soilink').click(function() {
   $('#soi').fadeTo(400, 1);
});

If you are trying create a toggle effect, there is also a fadeToggle() function.

$('#soilink').click(function() {
   $('#soi').fadeToggle(400);
});

Update:

Here is how to do that.

$('#soilink').click(function() {
   $('#soi').stop().fadeTo(400, $('#soi').css('opacity') == 0 ? 1 : 0); 
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!