Myles
Myles

Reputation: 812

CSS3 crossfade simialr to setinterval

I'm trying to achieve a similar effect to the JS setinterval/settimeout but using CSS3. So far I have achieved the desired effect, but only with :hover. How can I have this work so that the animation will just run every 3-4 seconds, without the need to hover?

Consider:

<div id="crossfade">
    <img class="bottom" src="http://www.boohoo.com/content/ebiz/boohoo/resources/images    /topbanners/Offer_Strip_GBP_v1.jpg" />
    <img class="top" src="http://www.boohoo.com/content/ebiz/boohoo/resources/images/topbanners/Offer_Strip_EUR_v1.jpg" />
</div>

And:

#crossfade {
    position:relative;
    height:250px;
    width:400px;
}
#crossfade img {
    position:absolute;
    left:0;
    opacity: 1;
    -webkit-transition: opacity 1s ease-in-out;
    -moz-transition: opacity 1s ease-in-out;
    -o-transition: opacity 1s ease-in-out;
    -ms-transition: opacity 1s ease-in-out;
    transition: opacity 1s ease-in-out;
}
#crossfade img.top:hover {
    opacity:0;
}

And a fiddle: http://jsfiddle.net/qEwPb/

Upvotes: 0

Views: 308

Answers (1)

Passerby
Passerby

Reputation: 10080

Extending from comment:

You can use CSS3 animation

Online demo

#crossfade img {
    position:absolute;
    left:0;
}
#crossfade img.top {
    -webkit-animation-name:pulse;
    -webkit-animation-iteration-count:infinite;
    -webkit-animation-timing-function:ease-in-out;
    -webkit-animation-duration:1s;
    -webkit-animation-direction:alternate;

    animation-name:pulse;
    animation-iteration-count:infinite;
    animation-timing-function:ease-in-out;
    animation-duration:1s;
    animation-direction:alternate;
}

@-webkit-keyframes pulse {
    0% {
        opacity:1;
    }
    100% {
        opacity:0;
    }
}
@keyframes pulse {
    0% {
        opacity:1;
    }
    100% {
        opacity:0;
    }
}

Browser compatibility

Adjust animation-duration to fit your need.

Edit:

If you want to stay at e.g. transparent for a few seconds, use something like this:

img.top {
    animation-duration:5s;
}
@keyframes pulse {
    0% {
        opacity:1;
    }
    20% {
        opacity:0;
    }
    100% {
        opacity:0;
    }
}

Upvotes: 1

Related Questions