Transforming clicks into JS function

Asked

Viewed 87 times

1

I’m trying to turn my clicks into functions, since the code is repeating itself in

https://github.com/rg3915/fs2w/blob/gh-pages/js/main.js

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';
    }
  })
});

That’s the code I wanted to make:

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

$("#div1").click(myfunc("#widget-body1"));

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 the ^= jQuery. So the event headphones are 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>
  <button type="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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.