Tommie Michael Lagerroos Tommie Michael Lagerroos - 6 months ago 10
Javascript Question

When div is clicked - slidetoggle other div

I have a problem with my jQuery code, I want the page to slideToggle one div ones the other is clicked, the problem is that I don't want to write all the code again and again so I tried to create a code that works all the time, but I'm stuck. Box is the div which should be clicked and it should contain a class that's also used on the div that's gonna slideToggle. It should pull the class from the tab and then use it to slideToggle the right object. Please help :S (the elements are not placed close to each other which makes next or children not possible). If you have any questions - ASK!

The jQuery code of mine:

$(".box").click(function() {
var Klassen = $(this).attr("class");
$("Klassen").slideToggle(300);
});


HTML:

<!-- These should be clicked -->
<div data-toggle-target="open1" class="box ft col-lg-3">
<div class="mer">
Läs mer
</div>

<div class="bild"><img src="images/sakerhet.jpg"></div>

<h4>HöstlovsLAN</h4>
</div>
</a>
<div data-toggle-target="open2" class="box st col-lg-3">
<div class="mer">
Läs mer
</div>

<div class="bild"><img src="images/sakerhet.jpg"></div>

<h4>NyårsLAN</h4>
</div>
<div data-toggle-target="open3" class="box tt col-lg-3">
<div class="mer">
Läs mer
</div>

<div class="bild"><img src="images/sakerhet.jpg"></div>

<h4>Säkerhet</h4>
</div>
<!-- These should be toggled -->
<div class="infobox" id="open1">
<h1>HöstlovsLAN</h1>
</div>
<div class="infobox" id="open2">
<h1>NyårsLAN</h1>
</div>
<div class="infobox" id="open3">
<h1>Säkerhet</h1>
</div>


EDIT - NEW PROBLEM - STILL AIN'T WORKING!

The code didn't work in my situation and would like you to take a look at the JS-fiddle I created:
http://jsfiddle.net/Qqe89/

Answer

undefined has presented the solution.

I would warn you about using this approach, if you add any classes to the .box div then your code will break.

Instead consider using data attributes to target the div to be toggled:

<div data-toggle-target="open1" class="box green"></div>

<div id="open1">
    Opens
</div>

Which can then target with

$('.box').click(function (e) {
    $( '#' + $(this).data('toggleTarget') ).slideToggle(300);
});

jsFiddle with example using your html - crudely formatted sorry!

Comments