Shortcircuit
Shortcircuit

Reputation: 71

Loop .click Function in Javascript

I would like to figure out how to loop a .click function with the slideToggle. Here's the code for the single event:

$("#slide1").click(function () {
  $("#panel1").slideToggle(1000);
});

slide1 is the div the person would click on toggling the panel to slide down or up. I've tried a for loop and etc to figure out how to loop this for multiple slide's and panels.

Say I have 10 slides is it possible to create one loop for all 10 or does it have to be done individually?

Upvotes: 1

Views: 173

Answers (3)

moonlight
moonlight

Reputation: 359

What you need is delegate. This will handle any events for any of the children. The first argument is a filter for which children you want to listen to. In this case you only want to capture events for .slides. The second argument specifies the type of event you want to listen to, here you need click as you only need click events. The last argument is the handler. In this handler function this refers to the element that has been clicked on.

$('#container').delegate('.slide', 'click', function(event) {
  $($(this).data('toggle')).slideToggle(1000);
});
.slide {
  width: 100px;
  height: 40px;
  background-color: #AAA;
  margin: 4px;
  padding: 4px;
}
.panel {
  width: 200px;
  height: 80px;
  background-color: #44A;
  margin: 8px;
  padding: 4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="container">
  <div class="slide" data-toggle="#panel1">Toggle panel 1</div>
  <div class="slide" data-toggle="#panel2">Toggle panel 2</div>
  <div class="slide" data-toggle="#panel3">Toggle panel 3</div>
  <div class="panel" id="panel1">Panel 1</div>
  <div class="panel" id="panel2">Panel 2</div>
  <div class="panel" id="panel3">Panel 3</div>
</div>

You can add as many slides and panels as you want (also dynamically), delegate will handle any click events on a .slide.

Upvotes: 0

user2120121
user2120121

Reputation: 655

You can make it in a more dynamic way:

$(".slide").click(function() {
  $("#"+$(this).attr("data-panel")).slideToggle(1000);
});

I hope that helps, good luck

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

The tidy way of doing this:

<div class="slide" data-panel="panel1">...</div>
<div id="panel1">...</div>

Build your slides like that. Then one handler is all you need:

$(".slide").click(function() {
    $("#"+this.getAttribute("data-panel")).slideToggle(1000);
});

Upvotes: 1

Related Questions