0

I am doing a comment system for my webpage. The website shows a group of elements from the database, that everyone can comment:

Element 1 ($element_id=1)-> Read comments...

Element 2 ($element_id=2)-> Read comments...

Element 3 ($element_id=3)-> Read comments...

When someone want to read comments of one element, can click in the "Read comments...", and a new div opens:

<div class="comments_more" id="comments_more"> Read comments...
<div class="comments_div" id="comments_div" > 
<?php include/comments.php ?>
<?php echo $element_id; ?>
</div> </div>

The jquery code to open the div works perfect for every element:

  $(document).ready(function(){
    $( '.comments_more' ).click(function() {
    $(this).find( '#comments_div' ).show('slide');
    });
    })

Now, I found a nice jquery to close the div when user clicks outside of it:

$(document).mouseup(function (e){
var container = $("#comments_div");
if (!container.is(e.target) // if the target of the click isn't the container...
    && container.has(e.target).length === 0) // ... nor a descendant of the container
{        container.hide();    }
});

The problem is that it only works for the first "Read comments..." (first element).

Kalimero
  • 1
  • 3
  • Possible duplicate of [Can multiple different HTML elements have the same ID if they're different elements?](http://stackoverflow.com/questions/5611963/can-multiple-different-html-elements-have-the-same-id-if-theyre-different-eleme) – Ionut Necula Apr 05 '17 at 10:33

2 Answers2

2

You can't have multiple IDs on one page, try using a class as a selector instead like:

$(".comments_div")
bhansa
  • 7,282
  • 3
  • 30
  • 55
Paul
  • 1,412
  • 1
  • 9
  • 19
0

I'm guessing here at what the repeated HTML looks like, but try something like this:

$(document).ready(function() {
  $('.comments_more').click(function() {
    $(this).find('.comments_div').show('slide');
  });
})

$(document).mouseup(function(e) {
  var container = $(".comments_div");
  if (!container.is(e.target) && container.has(e.target).length === 0)
  {
    container.hide();
  }
});
.comments_div {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="comments_more"> Read comments...
  <div class="comments_div">
    Comments 1
  </div>
</div>
<div class="comments_more"> Read comments...
  <div class="comments_div">
    Comments 2
  </div>
</div>
<div class="comments_more"> Read comments...
  <div class="comments_div">
    Comments 3
  </div>
</div>
Arg0n
  • 8,283
  • 2
  • 21
  • 38