Transforming clicks into JS function

1

I'm trying to turn my clicks into functions, since the code is being repeated in

link

This is the original code:

$("#div1").click(function() {
  $("#widget-body1").slideToggle("slow");
});

$("#toggle1").click(function() {
  $("#widget-body1").slideToggle("slow");

  $('#toggle1').toggleClass(function() {
    if ($(this).is('.fa fa-chevron-down')) {
      return '.fa fa-chevron-up';
    } else {
      return '.fa fa-chevron-down';
    }
  })
});

This is the code I wanted to do:

function myfunc(par1) {
  $(par1).slideToggle("slow");
};

$("#div1").click(myfunc("#widget-body1"));
    
asked by anonymous 02.04.2017 / 02:25

1 answer

2

If I understand correctly you want to apply the DRY idea in this code to avoid repetition.

A useful thing, if you are using different IDs and with a number to distinguish each element is to use ^= of jQuery. Thus the event headphones become generic.

Suggestion:

function toggle(e) {
  var id = e.currentTarget.id;
  var nr = id.match(/\d+$/)[0]; // aqui extrais o numero do ID
  $('#widget-body' + nr).slideToggle('slow');
}

$('[id^=div]').click(toggle);
$('[id^=toggle]').click(function(e) {
  toggle(e);
  $(this).toggleClass('fa-chevron-up fa-chevron-down');
});
div.fa-chevron-up {
  display: none;
  padding: 10px;
  margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><section><buttontype="button" id="div1">Toggle</button>
  <div id="widget-body1" class="fa fa-chevron-up">
    Olá!
    <button type="button" id="toggle1">Fechar</button>
  </div>
</section>

<section>
  <button type="button" id="div2">Toggle</button>
  <div id="widget-body2" class="fa fa-chevron-up">
    Olá!
    <button type="button" id="toggle2">Fechar</button>
  </div>
</section>

<section>
  <button type="button" id="div3">Toggle</button>
  <div id="widget-body3" class="fa fa-chevron-up">
    Olá!
    <button type="button" id="toggle3">Fechar</button>
  </div>
</section>
    
02.04.2017 / 07:54