index.html
<script>
function hide_image() {
var show = document.getElementById("showimage");
if(show.style.display === "none")
show.style.display = "block";
else
show.style.display = "none";
}
</script>
{% block content %}
<center>
{% for post in post_list %}
{{post.user.username}}
<br>
{{post.date_time}}
<br>
{{post.content}}
<br>
<button id="hide_image" onclick="hide_image()">Hide</button>
{% for image in post.postimage_set.all %}
<img id="showimage" src="{{image.images.url}}" alt="postimage" style="width: 300px;">
{% endfor %}
<br>
{% for file in post.postfile_set.all %}
<a href="{{file.files.url}}">{{file.files}}</a>
{% endfor %}
<br>
<a href="{% url 'comment' post.id %}">Comment</a>
<hr>
{% endfor %}
</center>
{% endblock %}
I am trying to hide the images when the hide button is clicked but when I am clicking the hide button of any image element then only the images of first element are hiding. Why is this happening? Can anyone explain?
CodePudding user response:
in your block content, make a different class name in all images with post id. Also pass the post id to the hide_image function
to catch related images:
<button id="hide_image" onclick="hide_image({{post.id}})">Hide</button>
<img src="{{image.images.url}}" alt="postimage" style="width: 300px;">
then in your scripts, select and make operation for all related images to the clicked button:
<script>
function hide_image(id) {
var shows = document.querySelectorAll(`.showimage-${id}`);
shows.forEach(show => {
if(show.style.display === "none")
show.style.display = "block";
else
show.style.display = "none";
})
}
</script>
CodePudding user response:
in hide_image function use document.querySelectorAll()
instead of document.getElementById()
then use a for loop or forEach
to implement if statement
CodePudding user response:
define an int in the for loop and increment it by one then pass it to the image id and hide_image function to allow the function to identify the selected image correctly for example
<button id="hide_image" onclick="hide_image({{i}})">Hide</button>
<img id="showimage{{i}}" src="{{image.images.url}}" alt="postimage" style="width: 300px;">
<script>
function hide_image(var x) {
var show = document.getElementById("showimage" x);
if(show.style.display === "none")
show.style.display = "block";
else
show.style.display = "none";
}
</script>