Question

I'm new to jQuery and I'm working on a text fader. This is the structure:

HTML:

            <section id="header-fader">
    <h2 id="h2-1" class="fader-h2 fader-all">Title 1</h2>
    <p id="p-1" class="fader-p fader-all">text 1</p>    

    <h2 id="h2-2" class="fader-h2 fader-all">title 2</h2>
    <p id="p-2" class="fader-p fader-all">text 2</p>    

    (more h2 and p goes here)

    </section>

jQUery

$(document).ready(function() {

$('#h2-1').delay(1000).fadeIn(2000);
$('#p-1').delay(3000).fadeIn(2000);
$('fader-all').delay(5000).fadeOut(2000);


$('#h2-2').delay(8000).fadeIn(2000);
$('#p-2').delay(10000).fadeIn(2000);
$('.fader-all').delay(1000).fadeOut(2000);

(more goes here)

});

The idea is for h2 and p to fadeIn one after another, and then for both of them to fadeOut at the same time.

So far I've achieved half - fades in, then

fades in, but then they fade out one after another instead of fading out simultaneously. It looks ugly, as when h2 fades out, it makes the space for p, which jumps up - not something I want to see on my website.

What am I doing wrong? I'm stuck with this for days and I've been postponing it, focusing on other aspects of the page, but now's the time it should really start working.

Help appreciated!

Était-ce utile?

La solution 2

You could add the delays and fade-outs at the same time, like this DEMO:

$(document).ready(function () {

    $('#h2-1').delay(1000).fadeIn(2000).delay(2000).fadeOut(2000);
    $('#p-1').delay(3000).fadeIn(2000).fadeOut(2000);


    $('#h2-2').delay(8000).fadeIn(2000).delay(2000).fadeOut(2000);
    $('#p-2').delay(10000).fadeIn(2000).fadeOut(2000);

});

Also, if you want them to fade in from the start, they should be hidden from the start. I've added style="display:none;" to all elements in the fiddle, but you could handle it with jQuery as well.

Autres conseils

firstly, you should use position absolute so they don't jump /move around at all from where they should be.

Then the reason it's not working on both fading out at the same time is because you use the individual id to fade them in, so stick with that on fading them out. I corrected this below, and set the timings so they'll fade out at the same time now.

$(document).ready(function() {

$('#h2-1').delay(1000).fadeIn(2000);
$('#p-1').delay(3000).fadeIn(2000);
$('#h2-1').delay(2000).fadeOut(2000);
$('#p-1').fadeOut(2000);

$('#h2-2').delay(8000).fadeIn(2000);
$('#p-2').delay(10000).fadeIn(2000);
$('#h2-2').delay(2000).fadeOut(2000);
$('#p-2').fadeOut(2000);

});

I've made a jsFiddle here.

The code:

var hDelay = 1000,
    pDelay = 3000,
    fadeOutDelay = 6000;

$('#h2-1').delay(hDelay).fadeIn(2000);
$('#p-1').delay(pDelay).fadeIn(2000);

$('#h2-1').delay(fadeOutDelay - hDelay).fadeOut(2000);
$('#p-1').delay(fadeOutDelay - pDelay).fadeOut(2000);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top