Search code examples
laravelimage-loading

Load image only when opening the modal in Laravel


Description

I have a small preview picture and when clicking on it, a modal opens with a bigger image.

<a onClick="ToggleImage()" class="toggle-img-btn">
<img class="about-img" src="{{asset("storage/images/about_170.jpg")}}" /></a>

@include('inc.imageModal')

And the image modal:

<div class="img-modal-background" id="img-modal-background">
  <div class="img-modal-content">
    <input type="checkbox" class="img-close" onClick="ToggleImage()" />
    <a class="img-close-cross"></a>
    <img class="modal-img" src="{{asset("storage/images/about.jpg")}}">
  </div>
</div>

And the JavaScript function for opening/closing the modal:

function ToggleImage() {
    const modalBG = document.getElementById("img-modal-background");
    const modalIMG = document.querySelector(".modal-img");
    if (modalBG.style.display === "flex") {
        modalBG.style.opacity = "0";
        setTimeout(() => {
            modalBG.style.display = "none";
            modalIMG.style.display = "none";
        }, 500);
    } else {
        modalBG.style.display = "flex";
        modalIMG.style.display = "inherit";
        setTimeout(() => {
            modalBG.style.opacity = "1";
        }, 10);
    }
}

Question

I only want to load the image in the modal, when the user opens the modal.

How can i achieve this?

I use Laravel 7 and plain JS.

You can find the repo here

Thanks for your time :)


Solution

  • you can put your image path on js variable and set attribute img src depend modal status like this :

    function ToggleImage() {
    const modalBG = document.getElementById("img-modal-background");
    const modalIMG = document.querySelector(".modal-img");
    const img = "storage/images/about.jpg";
    
    if (modalBG.style.display === "flex") {
        modalBG.style.opacity = "0";
        modalIMG.setAttribute("src", "");
        setTimeout(() => {
            modalBG.style.display = "none";
            modalIMG.style.display = "none";
        }, 500);
    } else {
        modalBG.style.display = "flex";
        modalIMG.style.display = "inherit";
        modalIMG.setAttribute("src", img);
        setTimeout(() => {
            modalBG.style.opacity = "1";
        }, 10);
    }
    

    }