Question

I'm trying to slideToggle with multiple divs, but I can't seem to get it to work.

I've gotten the basic functionality of what I want in a 2 div layout:

http://jsfiddle.net/q6smW/

$(".replication").slideUp(500,function(){
    $(".duplication").slideToggle(500)
});

But I need it to work with 3 or 4 divs instead of just 2.

I almost feel like the code should be similar to this:

$(".replication").slideUp(500, function($(".duplication").slideUp(500,function()){    
     $(".thirdclass").slideToggle(500)
});

Any help is appreciated.

Was it helpful?

Solution 2

I suggest wrapping your image divs in a container, and doing the same to your info divs. Either you use the same container or two separate--up to you. Then use when an image div is clicked, hide all your info divs, and show only the corresponding info div, by way of using the index of div relative to the container. You can use jQuery's index() function. It also simplifies your code.

OTHER TIPS

Basically you need to make everything generic to handle it with common ground.

Firstly, I would alter your markup to be something like this, note the data attributes:

<div class="dupImage img" data-menu="duplication"><img /></div>
<div class="repImage img" data-menu="replication"><img /></div>

<div class="menuitem" id="duplication">
    <h3>Duplication</h3>
    <ul>
        <li>CDs, DVDs or Blu-Rays</li>
        <li>CDs, DVDs or Blu-Rays</li>
    </ul>
</div>

<div class="menuitem" id="replication">
    <h3>Replication</h3>
    <ul>
        <li>CDs, DVDs or Blu-Rays</li>
        <li>CDs, DVDs or Blu-Rays</li>
    </ul>
</div>

Then condense your script to something like this:

var menu;
$(document).ready(function(){
    $('.menuitem').hide();
    $('.img').click(function () {
        menu = $("#" + $(this).data("menu"));
        $(".menuitem:not(#" + menu.attr("id") + ")").slideUp(500,function(){
             menu.slideDown(500);
        });
    });   
});

Here is a fiddle:

http://jsfiddle.net/MXusL/1/

I hope this helps, good luck with your app!

Based on Moby's answer small improvement so that you can toggle active one , otherwise you cant close it once it is open.

http://jsfiddle.net/jhYq5/2/

var menu;
$(document).ready(function () {
    $('.menuitem').hide();
    $('.img').click(function () {
        menu = $("#" + $(this).data("menu"));

        $(".menuitem:not(#" + menu.attr("id") + ")").slideUp();
        menu.slideToggle();


    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top