Grégoire Dpy
Grégoire Dpy

Reputation: 1

same event, same effect, multiple IDs

I am trying to minify this code with a function. I have multiple IDs.

// opening section
$("#id").click(function() {
  if ($("#id2").is(":hidden")) {
    $("#id2").slideDown("fast");
  }); 

  $("#id3").click(function() {
    if ($("#id4").is(":hidden")) {
      $("#id4").slideDown("fast");
    }); 

    $("#id5").click(function() {
      if ($("#id6").is(":hidden")) {
        $("#id6").slideDown("fast");
      });

Upvotes: 0

Views: 415

Answers (3)

Bijan Rafraf
Bijan Rafraf

Reputation: 385

You could assign an attribute to the #id element to signify the corresponding #id2 element and so on:

<div id="id" class="click-div-button" data-clickdiv="id2">

Then your jquery is simply

$(".click-div-button").click(function() {
  var data=$(this).data('clickdiv')
  if ($('#'+ data).is(":hidden")) {
    $('#'+ data).slideDown("fast");
  }); 

This will pick up the correct divs to trigger on due to their class and puck up the right divs to act on based on the attribute.

Upvotes: 1

Renzo Calla
Renzo Calla

Reputation: 7696

Using jquery

// opening section
  
function slideDown(e) {
  var id = $(e.target).attr('id').replace('id','');
      id = id==''?2:parseInt(id)+1; 
  console.log('will slidown this:',id);
  if ( $( "#id"+id ).is( ":hidden" ) ) {
    $( "#id"+id ).slideDown( "fast" );
  }  
}
$( "#id" ).click(slideDown);
$( "#id2" ).click(slideDown);
$( "#id3" ).click(slideDown);
$( "#id4" ).click(slideDown);
$( "#id5" ).click(slideDown);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id">1</div>
<div id="id2">2</div>
<div id="id3">3</div>
<div id="id4">4</div>
<div id="id5">5</div>
<div id="id6">6</div>

Upvotes: 1

justin
justin

Reputation: 439

You could create a forEach loop to generate each event.

Because of the inconsistent format (id -> id2) I am creating an object that maps to the next id.

const idMatch = {
  id:  'id2',
  id2: 'id3',
  id3: 'id4',
  id4: 'id5',
  id5: 'id6'
};

Object.keys(idMatch).forEach((key) => {
  const nextKey = $('#' + idMatch[key]);
  const currentKey = $('#' + key);

  currentKey.click(function() {
    if (nextKey.is(":hidden")) {
      nextKey.slideDown("fast");
    }
  });
});

Upvotes: 0

Related Questions