1

Hey Guys I am having trouble fading out a Div in my HTML document. I am able to use the same function reversed and am able to fade the divs in as required but not out. Any ideas?

Here is the JavaScript function:

function fadeOut(node, duration) {
    var increments = 100;
    var increment_value = 1/increments;
    var interval = duration/increments;
    var opacity = 1;

    var repeater = setInterval( function() {
        if (opacity > 0) {
            opacity = opacity - increment_value;
            node.style.opacity = opacity;
        } else {
            clearInterval(repeater);
        }
    }, interval);
}
5
  • Whats the code for your fadeIn which is working. Are you sure it's being stopped? I'd say it's quite likely your fadeIn interval is still going and the 2 events are just cancelling each other out. Can you make a jsfiddle demonstrating the problem? Commented Sep 4, 2014 at 11:36
  • BTW, there's no need to use extra variable for opacity value. And don't forget to set opacity equals zero at last iteration. Commented Sep 4, 2014 at 11:41
  • Why not use jQuery fadeIn()? Commented Sep 4, 2014 at 11:42
  • seems to be working fine. Commented Sep 4, 2014 at 11:46
  • 2
    @SyedAliTaqi are you suggesting to use a huge library for a tiny piece of code? i'd ask why not use css transition instead... Commented Sep 4, 2014 at 11:47

1 Answer 1

2

You can use css-transitions to fade in/out (in other words: leave the actual fading to the browser):

Let's have an element

<div id="fader"> fader
  <div data-dofade="1">Let us fade in/out</div>
</div>

For this element the following css

#fader div {
    opacity: 1;
    transition: all ease-in 1s 0s;
}

#fader div.fadeout {
    opacity: 0;
    transition: all ease-out 1s 0s;
}

Now you can use this handler to fade the div within div#fader in or out:

document.querySelector('#fader').addEventListener(
        'click',  
        function(e){
          var fadeEl =  this.querySelector('[data-dofade]');
          fadeEl.className = /fadeout/i.test(fadeEl.className)  ? '' : 'fadeout';
        }
);

Feel free to fiddle around with it in this jsFiddle (contains a scripted fader too).

See also: css transition (MDN)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.