0

I would like to slide divs, all of them will have same id because they'll generate inside loop so also trigger has same id. That's why I want to use one function, at the moment function works only for first div and I have no idea how to fix it. I would like that each button would work for div above him.

html part

<div id='slide'>
hello
</div>
<p id='but'>click</p>

<div id='slide'>
hello
</div>
<p id='but'>click</p>

and the js

$(document).ready(function(){
$(this).click(function(){
    $("#slide").slideToggle("slow");
    });
});
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
  • The problem is that you have duplicate IDs on the same page. This is invalid markup. Please consider using classes instead. – Obsidian Age Jan 19 '18 at 00:13
  • 1
    use `$(".slide").slideToggle("slow");` and `
    `
    – Ivan86 Jan 19 '18 at 00:14
  • See [**this post**](https://stackoverflow.com/questions/5611963/can-multiple-different-html-elements-have-the-same-id-if-theyre-different-eleme) on why you can't have duplicate IDs. – Obsidian Age Jan 19 '18 at 00:15
  • but if I would do like that then one button will slide all divs and I want one button work on one div, any other solution ? – user2759825 Jan 19 '18 at 00:17

2 Answers2

0

Few issues:

Use classes not IDs and use the ID of the click element #but instead of this for your click function

<div class='slide'>
hello
</div>
<p class='but'>click</p>

<div class='slide'>
hello
</div>
<p class='but'>click</p>

$(document).ready(function(){
    $('.but).click(function(){
       $(".slide").slideToggle("slow");
    });
});
Pixelomo
  • 6,373
  • 4
  • 47
  • 57
  • you say _Use classes not IDs_... the reason is so the `ids` don't duplicate, yet you have two `id="but"`. – Ivan86 Jan 19 '18 at 00:25
0

First of all, don't have same ids on one page - use classes instead. If you want to do something with the element before clicked item, you can use prev(), something like this (in your code just change css('color', 'red') to slideToggle("slow"), I have added it just for example):

$(document).ready(function() {
  $(".but").click(function() {
    $(this).prev().css('color', 'red');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='slide'>
  hello
</div>
<p class='but'>click</p>

<div class='slide'>
  hello
</div>
<p class='but'>click</p>
P.S.
  • 15,970
  • 14
  • 62
  • 86