Skip to content
Advertisement

Read More js in django for loop

I try to apply this post to integrate read more/read less JS into a django template. I want to limit my post app. 200 characters and providing the user the option to Read More.

This script seems to work fine… not so much in my case. It displays the Read More option but once clicked no event it triggered. That is, it doesn’t open the entire text. It displays a colored test ‘Read More’ but noting else happens.

Here’s the answer provided in that post:

{% for post in posts %}
    {% if post.content|length > 150 %}
        <p class="half-content" id="half-{{post.id}}">{{ post.content|truncatechars:150 }}<a data-id="{{post.id}}" href="javascript:void();" class="show-hide-btn">read more</a></p>
        <p class="full-content" id="full-{{post.id}}" style="display: none;">{{ post.content }}</p></div>
    {% else %}
        <p>{{ post.content }}</p>
    {% endif %}
{% endfor %}


<script>
    $(document).ready(function(){
        $(".show-hide-btn").click(function(){
            var id = $(this).data("id");
            $("#half-"+id).hide();
  

Any input is highly appreciated.

Advertisement

Answer

You need to show other i.e : full-content when you click on readmore so you can use $("#full-" + id).toggle(); .Also , i have added read less text to hide the text which is display .You can add that part here :

 <p class="full-content" id="full-{{post.id}}" style="display: none;">{{ post.content }}<a data-id="{{post.id}}" href="javascript:void();" class="show-hide-btn">read less</a></p>

Demo Code :

$(document).ready(function() {
  $(".show-hide-btn").click(function() {
    var id = $(this).data("id");
    $("#half-" + id).toggle();//hide/show..
    $("#full-" + id).toggle();
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<p class="half-content" id="half-1">Yes ,you..<a data-id="1" href="javascript:void();" class="show-hide-btn">read more</a></p>
<p class="full-content" id="full-1" style="display: none;">Yes,you..are aweome<a data-id="1" href="javascript:void();" class="show-hide-btn">read less</a></p>
<p class="half-content" id="half-3">Yes..you..<a data-id="3" href="javascript:void();" class="show-hide-btn">read more</a></p>
<p class="full-content" id="full-3" style="display: none;">Yes ..you..can do it..<a data-id="3" href="javascript:void();" class="show-hide-btn">read less</a></p>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement