Igor Levashov
Igor Levashov

Reputation: 328

Getting id of collapsible div in Jquery and Bootstrap

I have multiple(it can be 100+) collapsible div (using bootstrap)

<div>
    <a href="#id1" data-toggle="collapse">
       <div class="col-lg-12">Title</div>
       <div class="image">Image</div>
    </a>
    <div id="id1" class="collapse">
       <div class="col-lg-12">Description</div>
    </div>
</div>
<div>
    <a href="#id2" data-toggle="collapse">
       <div class="col-lg-12">Title</div>
       <div class="image">Image</div>
    </a>
    <div id="id2" class="collapse">
       <div class="col-lg-12">Description</div>
    </div>
</div>

And have Jquery

$('#id1').on('show.bs.collapse', function () {
            $(".image").addClass('hidden');
        });

$('#id1').on('hidden.bs.collapse', function () {
        $(".image").removeClass('hidden');
    });

I want to add hidden class on show.bs.collapse(this is from bootstrap) and remove hidden class on hidden.bs.collapse'With the jq code above I can do this just with one div that has id1. But how can I do this independently?

Upvotes: 0

Views: 1754

Answers (2)

ams4fy
ams4fy

Reputation: 185

Try not to subscribe on the elements by ids but by element type

$('a').on('show.bs.collapse', function () {
    $(this).next().find("div.image")[0].addClass('hidden');
});

$('a').on('hidden.bs.collapse', function () {
    $(this).next().find("div.image")[0].removeClass('hidden');
});

Where

$(this)

should return a pointer to the collapsed/uncollapsed element

next()

should move pointer to the next element ( div id="id1" as example)

find("div.image")[0]

will find div with class "image" and take the first found element

then you can hide the image in this block or show it without using ids

If you're using

$(".image").addClass('hidden');

this will hide all the images in all blocks (not only in that one that has been collapsed)

Upvotes: 1

Farshad Momtaz
Farshad Momtaz

Reputation: 424

Id refers to one element on the DOM therefore you should use classes instead. Therefore you should select divs based on their classes.

The following is a possible solution:

<div>
    <a href="#id1" data-toggle="collapse">
       <div class="col-lg-12">Title</div>
    </a>
    <div class="some-class collapse ad-col-2">
       <div class="col-lg-12">Description</div>
       <div class="image"></div>
    </div>
</div>
<div>
    <a href="#id2" data-toggle="collapse">
       <div class="col-lg-12">Title</div>
    </a>
    <div class="some-class collapse ad-col-2">
       <div class="col-lg-12">Description</div>
       <div class="image"></div>
    </div>
</div>

Jquery:

$('.some-class').on('show.bs.collapse', function () {
        $(".image").addClass('hidden');
    });

$('.some-class').on('hidden.bs.collapse', function () {
    $(".image").removeClass('hidden');
});

Upvotes: 0

Related Questions