Skip to content
Advertisement

javascript button on clock

Now I have issue that only first clicked button works when pressing others post buttons after first clicked button, it just disappears and not loading comments,

Adding snipped to clarify issue. It’s first time using this feature. Sorry for issues, may you can help me with that.

I’m using django as backend.

var currentItems = 0;
            
function loadcomments(d) {
  var post = d.getAttribute("data-post");
  const elementList = document.querySelectorAll('#comment'+post);
  for (let i = currentItems; i < currentItems + 2; i++) {
    if (elementList[i]) {
      elementList[i].style.display = 'block';
    }  
  }
  currentItems += 2;
  if (currentItems >= elementList.length) {
    event.target.style.display = 'none';  
  }
}
.comment {
  display: none;
}
<div class='post'>
<div class='comment' id="comment1">
  11
</div>

<div class='comment' id="comment1">
  12
</div>

<div class='comment' id="comment1">
  13
</div>

<div class='comment' id="comment1">
  14
</div>

<div class='comment' id="comment1">
  15
</div>

<a class="loadmore" href="javascript:void(0)" 
onclick="loadcomments(this)" data-post="1">Load more</a>
</div>

<div class='post'>
<div class='comment' id="comment2">
  21
</div>

<div class='comment' id="comment2">
  22
</div>

<div class='comment' id="comment2">
  23
</div>



<a class="loadmore" href="javascript:void(0)" 
onclick="loadcomments(this)" data-post="2">Load more</a>
  
</div>

Advertisement

Answer

You need to set special currentItems variable for each posts.

remove the global currentItems variable and Try

function loadcomments(d) {
    var post = d.getAttribute("data-post");
    var currentItems = d.getAttribute("data-currentItems") | 0;
    const elementList = document.querySelectorAll('#comment'+post);
    for (let i = currentItems; i < currentItems + 2; i++) {
        if (elementList[i]) {
            elementList[i].style.display = 'block';
        }  
    }
    currentItems += 2;
    d.setAttribute("data-currentItems", currentItems);
    if (currentItems >= elementList.length) {
        event.target.style.display = 'none';  
    }
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement