1

I've implemented a fade-in effect using pure Javascript, but I yearn for something more native, like using CSS3. Is there a way to trigger the CSS fade-in effect from Javascript?

Thanks.

0

2 Answers 2

7

HTML:

<div id="foo" class="hidden">Hello!</div>

CSS:

div {
    -webkit-transition: opacity 1s linear;
}
.hidden {
    opacity: 0;
}

JS:

setTimeout(function() {
    document.getElementById('foo').className = '';
}, 1000);

http://jsfiddle.net/RYgsA/

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

2 Comments

Yay for vendor prefixes! -o-transition:
@AlexWayne Hi AlexWayne, I have the same question but am trying to figure out the next step. I have tried the jsfiddle code you posted, which works very well, but I am trying to adapt it to work more than once. I have a div element which I want to fade in every time a certain button is clicked. I tried re-adding the class 'hidden' but can't seem to get it to work more than the first time. Any suggestions would be appreciated.
2

here you go

HTML

<div id="box"></div>

CSS

#box {
    width: 100px;
    height: 100px;
    background-color: black;
    opacity: 1;
    -webkit-transition:opacity 0.5s linear;
    -moz-transition:opacity 0.5s linear;
    -o-transition:opacity 0.5s linear;
    -ms-transition:opacity 0.5s linear; 
    transition:opacity 0.5s linear;
}

JS

function fadde() {
        var box = document.getElementById('box');
        box.style.opacity = (box.style.opacity == 1) ? 0 : 1;   
}
setInterval(fadde, 1000);

example at

https://jsfiddle.net/z54a75os/

1 Comment

If I used setInterval() it flashes for me. So instead I use setTimeout().

Your Answer

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