Search code examples
jqueryeffects

Two jQuery effect with one click


I'm trying to make a template with jQuery accordion. i just need to open 2 different div with 2 different effect with one click.

My Codes:

jQuery:

$(document).ready(function() {
    $('div.question').click(function() {
        $('div.answer').slideUp(600);   
        $(this).next().slideDown(600);
    });
    $("div.answer").hide();
});

HTML:

<div class="question">Question</div>
<div class="answer">Answer</div>

but, I'm trying to make something like this, showing 2 div with 2 effect after click on question:

jQuery:

$(document).ready(function() {
    $('div.question').click(function() {
        $('div.answer').slideUp(600);   
        $('div.tip').fadeIn();  
        $(this).next().slideDown(600);
        $(this).next().fadeOut();
    });
    $("div.answer").hide();
    $("div.tip").hide();
});

HTML:

<div class="question">Question</div> <!--On click-->
<div class="answer">Answer</div> <!--Open with slide effect-->
<div class="tip">Tip</div> <!--Open with fade in effect-->

How i can show 2 DIV with 2 effects after click on question?

Demo with problem: http://jsfiddle.net/3RtKS/


Solution

  • I've updated a fiddle: http://jsfiddle.net/3RtKS/5/

    The gist is that you need two next's to find the hint and I swapped the fade in and fade out to be how I think you wanted them:

    $('div.question').click(function() {
        $('div.answer').slideUp(600);   
        $('div.tip').fadeOut();  
        $(this).next().slideDown(600);
        $(this).next().next().fadeIn();
    });
    

    I also created a second fiddle that I think is possibly a better and more contained way of doing this - next seems a little fragile.

    http://jsfiddle.net/3RtKS/3/

    This nests the answer and tip inside the question element (though you could add new elements). This has the advantage that you just need to find the tip and answer inside the question element clicked on to deal with.

    The script then becomes:

    $('div.question').click(function() {
        $('div.answer').slideUp(600);   
        $('div.tip').fadeOut();  
        $('div.answer', this).slideDown(600);
        $('div.tip', this).fadeIn();
    });
    

    and the HTML:

    <div class="question">Question 
        <div class="answer">Answer</div>
        <div class="tip">Tip</div>
    </div>
    

    In a final thing I'd probably have a few more divs (eg a questionText div) to make it easier to manage.