Vukasin
Vukasin

Reputation: 33

Passing img source value from one html page to another

I have two pages:
-projects page that contain a gallery of images imported from json file
-project page that will display single image that was clicked in projects page
I want to store and pass that clicked image src and import it in project page. I can't find a solution how to comunicate between two js files and two html files.
These are my codes:
projects.js

const projectsGallery = document.querySelector('.projects__wrapper');

axios
    .get('../data.json')
    .then(async response => await response.data)
    .then(data => {
        const displayProjects = function (project) {
            projectsGallery.innerHTML = ``;
            project.forEach(project => {
                const card = `
        <div class="card"> <form action="submit" method=POST>
                            <img src=${project.src} id="myImg" class="img__project gallery-img" alt=${project.alt}></img>
                            <h1  class="hvr-grow">${project.projectName}</h1>
                            <div class="card__btn-wrapper">
                                <a class="card__btn hvr-sweep-to-left" href=${project.code}>
                                See Code
                        </a>
                        <a class="card__btn hvr-sweep-to-right" href=${project.live}>
                            Live
                    </a>
                    </form>
                        </div>
                        </div>
        `;
                projectsGallery.insertAdjacentHTML(`beforeend`, card);
            });
            modalFunc();
        };
        displayProjects(data.projects);

        images.forEach(image => {
            image.addEventListener(`click`, function () {
                const images = document.querySelectorAll('.gallery-img');
                let img = image.src;
                window.document.location = `/pages/project.html`;
            });
        });
    });

project.js

let src = localStorage.getItem(`img`);
console.log(img);

Upvotes: 0

Views: 127

Answers (1)

Palash Kanti Bachar
Palash Kanti Bachar

Reputation: 616

Since your application is not in a single page application you are going to redirect new page so you need to store data in localStorage or sessionStorage.

Solution : Before redirecting the page store the data

localStorage.setItem(`img`, imageData);

and during render the new page get the data

let src = localStorage.getItem(`img`);

Upvotes: 1

Related Questions