gravition
gravition

Reputation: 113

Disable boostrap toggle collapse for one class and enable it for another

I have a boostrap collapse button that looks like this:

<button type="button" class="btn btn-info" data-toggle="collapse" data-target="#<?php echo $row['pid']; ?>">View more info</button>
    <div id="<?php echo $row['pid']; ?>" class="collapse">
        <?php
        //php code that display more info goes here
        }
        echo '</div>';
  ?>

when user click this button, more information about the picture will be revealed. Because each picture has unique information, the div id and data-target of this button has to be the id of the picture in the database, otherwise no accurate information can be displayed. However, I also have a like button, when a user clicked it, he will "liked" the picture, and it goes like this :

<button type="button" class="like" id="<?php echo $row['pid']; ?>">Like <span><?php echo likes($row['pid']); ?></span></button>

the id of the like button also has to be identical to the id of the picture in the database, because in the javascript code I use this id to know which picture's like button is being clicked, and then I can add the number of likes for that picture.

The problem is, both the like button and the collapse button have the same id(the id of the picture). When I clicked the collapse button, instead of showing more information about the picture, the number of likes is being hidden. I tried to disabled boostrap collapse based on classes by the following code :

<script>

    $('.like').bootstrapToggle('off');
   $('.collapse').bootstrapToggle('on');

</script>

but it's not working. If I delete the "like" button everything will work smoothly, but after adding the like button, the collapse button would hide the like button when it's clicked. What can I do to not the the collapse button interfere with the likes button?

Upvotes: 0

Views: 756

Answers (1)

partypete25
partypete25

Reputation: 4413

So here is an example where you use the same id :

ABCD1234

on both elements but on the like button you apply it as a data attribute. When the button is clicked, you retrieve the id via the data attribute and then use it as a selector to update the like count on the appropriate matching collapsed content based on that id.

HTML

<button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#ABCD1234" aria-expanded="false" aria-controls="collapseExample">
  Button with data-target
</button>
<div class="collapse" id="ABCD1234">
  <div class="well">
    <span>100</span> likes
  </div>
</div>

<br>
<button type="button" class="like" data-id="ABCD1234">Like <span>ABCD1234</span></button>

JS

$('.like').click(function(){
  var thisID = '#' + $(this).data('id');
  var $count = $('span', thisID);
  var number = parseInt($count.text());
  $count.text(number+1);
});

https://codepen.io/partypete25/pen/XgqBZX

Upvotes: 1

Related Questions