2

this if my first question here, so sorry for any mistake or if the question is too silly.

*I have a Class with a method that displays a country-card on screen. I need to add an onclick function to save the name of the country so I can access to it from another page. i don't know if there is a way to make it work.

Any ideas?

class UI {
    constructor() {
         this.cardsContainer = document.querySelector("#cards-container");
     }

    showCountries(data) {
        data.forEach(country => {
            let div = ` 
            <div class="card">
                // this is the onclick function i need to access  
                <a onclick="countrySelected(${this.country.borders})"> 

                <div class="card-image">
                <img src=${country.flag} alt="">
                </div>
                <div class="card-info">
                 <h2 class="card-name"> ${country.name}</h2>
                 <p><strong>Population:</strong> ${country.population}</p>
                 <p><strong>Region:</strong> ${country.region}</p>
                 <p><strong>Capital:</strong> ${country.bogota}</p>
                </div>
                </a>
            </div>
           `;
        this.cardsContainer.innerHTML += div;
      })
    }

    //method 
    countrySelected(data) {
        sessionStorage.setItem('country', data);
    }
}
Max Peng
  • 2,879
  • 1
  • 26
  • 43
Lucas Gomez
  • 98
  • 1
  • 6

1 Answers1

2

I assume that the country.name is unique.

class UI {
  constructor() {
    this.cardsContainer = document.querySelector("#cards-container");
  }

  showCountries(data) {
    data.forEach(country => {
      let div = ` 
            <div class="card">
                // this is the onclick function i need to access  
                <a id=${country.name}> 

                <div class="card-image">
                <img src=${country.flag} alt="">
                </div>
                <div class="card-info">
                 <h2 class="card-name"> ${country.name}</h2>
                 <p><strong>Population:</strong> ${country.population}</p>
                 <p><strong>Region:</strong> ${country.region}</p>
                 <p><strong>Capital:</strong> ${country.bogota}</p>
                </div>
                </a>
            </div>
           `;

      this.cardsContainer.innerHTML += div;
      document.querySelector(`a[id="${country.name}"]`)
              .addEventListener('click', () => countrySelected(country.borders));
    })
  }

  //method 
  countrySelected(data) {
    sessionStorage.setItem('country', data);
  }
}

Also, you can refer to this post: Setting HTML Button`onclick` in template literal

Max Peng
  • 2,879
  • 1
  • 26
  • 43