John Davidson

javascript - Popup modal with JS and PHP query

0 comments
Message:


I've got a gallery where I have some buttons to filter the images by category. When you click an image it pops up a modal and shows the picture. It works when I open it up (at first it shows all the images) and when I choose a option 2021, but with other options it does not work. The strange thing is that when I click an image from (for example) option 2020, the modal does not show up, but when I click option 2021 the modal with the right picture shows up.
The buttons look like this:


<button data-filter=".2020">2020</button>
<button data-filter=".2021">2021</button>

I read the picture's names from mysql database and shows it with a while loop with php.


query starts
echo '<div class="col-lg-3 col-md-6 special-grid '; echo $row["category"]; echo '">
...
<img id="myImg'; echo $db; $db++; echo'" src="gallery/'; echo $row["picturename"];
echo'" class="img-fluid" alt="Image" width="480" height="380">
query ends

Modal:


<div id="myModal" class="modal">
<span class="close">&times;</span>
<img class="modal-content" id="img01">
<div id="caption"></div>
</div>

Javascript:


<script>
var modal = document.getElementById("myModal");
var modalImg = document.getElementById("img01");
for (let i = 0; i < <?php echo $sizeofgallery ?>; i++) {
// Get the image and insert it inside the modal
var img = document.getElementById("myImg" + i);
img.onclick = function () {
modal.style.display = "block";
modalImg.src = this.src;
}
}
var span = document.getElementsByClassName("close")[0];
span.onclick = function () {
modal.style.display = "none";
}

</script>


My Answer:
html





_And the JavaScript code for filtering and displaying the modal:_

javascript
$(document).ready(function(){
$('.filter-button').click(function(){
var filterValue = $(this).data('filter');
$('.gallery-item').hide();
$('.gallery-item[data-category="' + filterValue + '"]').show();
});

$('.gallery-item').click(function(){
var imageSrc = $(this).find('img').attr('src');
$('#modal-image').attr('src', imageSrc);
$('#myModal').modal('show');
});
});


_Make sure that each image in your gallery has a `data-category` attribute with the corresponding category value (e.g. `data-category="2020"` for images from 2020). This way, the filtering will work correctly and the modal will display the correct image when clicked._

Rate this post

3 of 5 based on 7460 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us