2

I have 2 classes in my HTML document: links and elements. I want to toggle specific element when specific link is clicked.
I have tried this:

var links = $('.links');
var elements = $('.elements');

for (var i = 0; i < links.length; i++) {
    links.eq(i).click(function() {
        elements.eq(i).toggle();
        return false;
    });
}
Regent
  • 5,142
  • 3
  • 21
  • 35

2 Answers2

1

Here the problem is the closure variable in a loop.

But we can solve it using index() like

var links = $('.links');
var elements = $('.elements');

links.click(function () {
    elements.eq(links.index(this)).toggle();
    return false;
})

var links = $('.links');
var elements = $('.elements');

links.click(function() {
  elements.eq(links.index(this)).toggle();
  return false;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a class="links">1</a>
<a class="links">2</a>
<a class="links">3</a>
<a class="links">4</a>
<a class="links">5</a>
<div class="elements">1</div>
<div class="elements">2</div>
<div class="elements">3</div>
<div class="elements">4</div>
<div class="elements">5</div>
Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

Another approach would be to use a data attribute to reference the id of the element in question.

<div class="container">
    <a class="links" data-element-id="el-1">Links</a>
    <span class="elemennts" id="el-1">Elements</span>
</div>
<script>
$('.container').on("click", ".links", function() {
    $("#" + $(this).data("element-id")).toggle();
}
</script>
user2182349
  • 9,569
  • 3
  • 29
  • 41