infox09 infox09 - 4 months ago 8
Javascript Question

fadeToggle of many element

please I want to apply fadeToggle for each button but it does not work with this method

this is Code HTML

<div id="ajouter" class="dropdown">
<ul>
<li>
<button class="projetbutton">Projet</button>
<form class="projet" style="display:none">
<input type="text" />
<input type="submit" />
</form>
</li>

<li>
<button class="famillebutton">Famille</button>

<form class="famille" style="display:none">
<input type="text" />
<input type="submit" />
</form>
</li>
</ul>
</div>


and this is script apply for the buttons

<script>
var classElement = ["projet", "famille"];
var button = "button";
for (var i = 0; i < classElement.length; i++) {
var classbutton = classElement[i].concat(button);

$(document).ready(function () {
$('.classbutton').click(function () {
$(".classElement[i]").fadeToggle();
});
});
}
</script>


Please if there is another method to do that job.

Answer

You can take advantage of the relation ship between element and various DOM traversal methods available to target element and then perform desired operation.

Associate the click handler using a common class, here used classbutton with the elements, then used .next() to get the form element.

$(document).ready(function() {
  $('.classbutton').click(function() {
    $(this).next().fadeToggle();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ajouter" class="dropdown">
  <ul>
    <li>
      <button type="button" class="classbutton">Projet</button>
      <form style="display:none">
        <input type="text" />
        <input type="submit" />
      </form>
    </li>

    <li>
      <button type="button" class="classbutton">Famille</button>

      <form style="display:none">
        <input type="text" />
        <input type="submit" />
      </form>
    </li>
  </ul>
</div>

Comments