HTML if div content is long show button

Viewed 61

I have this django app I made, and it is a blog app. The blogs are quite long, so I want to be able to show a little and then more of the div's text if the blog is long. Here is my html:

<a style="text-decoration: none;color: #000;" href="{%  url 'post-detail' post.id  %}">
   <div id="content-blog"><p class="article-content">{{ post.content|safe }}</p></div>
</a>

I want something like this:

<script>
content = document.getElementById("content-blog");
max_length = 1000 //characters
if(content > max_length){
//Do something
}
</script>

So how would I get this to actually work. To summarize, I want this to check if a div is longer than 1000 characters, and if it is, to run the if statement above. Thanks.

2 Answers

You need to use innerText, please change your JS code to

<script>

var content=document.getElementById("content-blog").innerText.length;

max_length = 1000 //characters
if(content > max_length){
//Do something
}
</script>

To get all the blogs and do something to them all:

let blogs = Array.prototype.slice.call(document.getElementsByClassName("article-content"));

blogs.forEach(blog => 
    if (blog.innerText.length > 1000) {

// Do stuff with the blog

    } else {}
)

You could also modify the context in your view, or add a model property to your blog mode, to make a preview_text for the blog post. Like post.content[:100] for first 100 characters of post.

Related