Snuur
Snuur

Reputation: 309

jquery finding previous class for slidetoggle

Im trying to get a div to slidetoggle, have made this before but then with clicking a tag, and having the next div slide open. Works fine every time. Now I have a button with class slideheader2 and above that a div with class slidecontent2 I want to slide open. There are multiple divs with multiple buttons on the page, that have that class.

Now this works:

jQuery(document).ready(function() {
jQuery(".slidecontent2").hide();
jQuery(".slideheader2").click(function()
{
$('div').prev(".slidecontent2").slideToggle(250);
 });
});

But it opens all the divs with that class on the page, not just the previous. I copied and modified this code from elsewhere, so i looked up .prev http://api.jquery.com/prev/ and modified the code like this, but now it doesnt work at all. Kinda lost here.

    jQuery(document).ready(function() {
   jQuery(".slidecontent2").hide();
   jQuery(".slideheader2").click(function()
   {
    $('div.slidecontent2').prev().slideToggle(250);
    });
    });

Hope someone can help me. Thanks.

@tymeJV

Sorry, that comment didnt work, thanks for your answer, but that code only works when theres nothing in between the slideheader2 and slidecontent2. For example the next piece of code wont work because of the otherdiv classed div in between. I need to have other divs in between the button and the sliding div.

<script>
jQuery(document).ready(function() {
  jQuery(".slidecontent2").hide();
  //toggle the componenet with class msg_body
  jQuery(".slideheader2").click(function()
  {
    $(this).prev(".slidecontent2").slideToggle(250);
  });
});

</script>

// works
<div class="slidecontent2" style="width: 500px; height:500px; border: 2px dotted black; background-color: red;">
<p>Slide1</p>
</div>
<input type="button" class="slideheader2" name="submitpakbon" id="submitpakbon" value="slide1" style="width: 225px; float: left;"/>

//wont work
<div class="slidecontent2" style="width: 500px; height:500px; border: 2px dotted black; background-color: red;">
<p>Slide2</p>
</div>
<div class="otherdiv"></div>
<input type="button" class="slideheader2" name="submitpakbon" id="submitpakbon" value="slide2" style="width: 225px; float: left;"/>

Upvotes: 0

Views: 97

Answers (2)

Snuur
Snuur

Reputation: 309

Found another solution. I give the name value of the button a unique number with php, give the id of the slidediv that number aswell and then use this code:

jQuery(document).ready(function() {

  jQuery(".slidecontent").hide();
  //toggle the componenet with class msg_body
  jQuery(".slideheader").click(function()
  {
  var $shipid = $(this).attr("name");
    $(".slideid"+$shipid).slideToggle(250);
  });
});

Upvotes: 0

tymeJV
tymeJV

Reputation: 104785

Use this:

jQuery(".slideheader2").click(function()
{
    jQuery(this).prev(".slidecontent2").slideToggle(250);
});

Upvotes: 1

Related Questions