I have created a for loop in Django which displays articles uploaded by users. In the case of long articles I will truncate the text to a max length of 150 chars, but want to give readers the option of expanding the text using a jquery function, by clicking 'read more'. This is my template:
{% for post in posts %}
{% if post.content|length > 150 %}
<p class="half-content">{{ post.content|truncatechars:150 }}<a href="javascript:void();" class="show-hide-btn">read more</a></p>
<p class="full-content" style="display: none;">{{ post.content }}</p>
{% else %}
<p>{{ post.content }}</p>
{% endif %}
{% endfor %}
And here is my jquery function:
$(document).ready(function(){
$(".show-hide-btn").click(function(){
$(".half-content").hide();
});
});
$(document).ready(function(){
$(".show-hide-btn").click(function(){
$(".full-content").show();
});
});
It works how I would like it to, except that the 'read more' link is expanding all the articles on the page, not just the one with the appropriate primary key. I know I need to include {{ post.id }} in my code somewhere, but so far everything I have tried has been ineffective.
try this,
{% 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();
$("#full-"+id).show();
});
});
</script>