JavaScript Найти индекс нажатой карты и сопоставить с модальной картой - PullRequest
0 голосов
/ 03 марта 2020

У меня проблема с проектом, над которым я работаю. В этом проекте мне нужно вывести на экран 12 карт случайных пользователей, что я и сделал. Затем мне нужно добавить модальное окно для них, и при нажатии на карточку пользователя, модальное окно должно появиться с информацией этого пользователя. Я создал функцию модального окна, и она работает.

Итак, проблема, с которой я столкнулся, - я не могу узнать, как отобразить информацию о пользователя с нажатой карточкой. В настоящее время, если я нажму на карточку второго или третьего пользователя, я получу всплывающее модальное окно первого пользователя.

Я знаю, что для этого мне нужно найти индекс нажатой карточки и проверить, соответствует индексу модальной карты. Но я изо всех сил пытаюсь это сделать.

Вот мой репозиторий GitHub ---> https://github.com/myndeks/PublicAPIRequests-Project5/blob/master/js/app.js

Может кто-нибудь мне помочь! Заранее спасибо!

/*---------------------------------------
                DOM
---------------------------------------*/

const gallery = document.getElementById('gallery');
const body = document.querySelector('body');

/*---------------------------------------
                Fetch data
---------------------------------------*/



fetch('https://randomuser.me/api/?results=12')
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    const results = data.results;
    userArray = [...results];

    generateHTML(userArray);
    displayModalWindow(userArray);
    addEventListenre();
  })

  /*---------------------------------------
      Add EVENT Listener for Modal
  ---------------------------------------*/


  function addEventListenre() {
    const cards = document.querySelectorAll('div.card');
    let cardsArray = [];
    cardsArray.push(cards);

    let modals = document.querySelectorAll('div.modal-container');

    for (var i = 0; i < cards.length; i++) {
      cards[i].addEventListener('click', (e) => {

        if (e.target.className === 'card') {
          const indexOfCards = Array.prototype.indexOf.call(cards, e.target);
          console.log(indexOfCards);

        }

      })
    }

  }

  /*---------------------------------------
                GenerateHTML
  ---------------------------------------*/

function generateHTML (data) {

  const employee = data.map(
    data => {
      const card = document.createElement('div');
      card.classList.add('card')
      gallery.appendChild(card);

      const cardImgContainer = document.createElement('div');
      cardImgContainer.classList.add('card-img-container');
      card.appendChild(cardImgContainer);

      const imageDiv = document.createElement('img');
      imageDiv.classList.add('card-img');
      imageDiv.src = data.picture.medium;
      cardImgContainer.appendChild(imageDiv);

      const cardINfoContainer = document.createElement('div');
      cardINfoContainer.classList.add('card-info-container');
      card.appendChild(cardINfoContainer);

      const nameDiv = document.createElement('h3');
      nameDiv.classList.add('card-name');
      nameDiv.textContent = data.name.first + data.name.last;
      cardINfoContainer.appendChild(nameDiv);

      const emailDiv = document.createElement('p');
      emailDiv.classList.add('card-text');
      emailDiv.textContent = data.email;
      cardINfoContainer.appendChild(emailDiv);

      const cityStage = document.createElement('p');
      cityStage.classList.add('card-text');
      cityStage.textContent = data.location.city + data.location.state;
      cardINfoContainer.appendChild(cityStage);
    }
  )
}


/*---------------------------------------
      Display  Modal Information
---------------------------------------*/
function displayModalWindow(data) {

  const employee = data.map(data => {
    const modalContainer = document.createElement('div');
    modalContainer.classList.add('modal-container');
    modalContainer.style.display = 'none';
    body.appendChild(modalContainer)

    const modal = document.createElement('div');
    modal.classList.add('modal');
    modalContainer.appendChild(modal);

    const button = document.createElement('button');
    button.classList.add('modal-close-btn');
    button.textContent = 'X';
    modal.appendChild(button);

    const modalInfoCotainer = document.createElement('div');
    modalInfoCotainer.classList.add('modal-info-container');
    modal.appendChild(modalInfoCotainer)

    const modalImage = document.createElement('img');
    modalImage.src = data.picture.medium;;
    modalInfoCotainer.appendChild(modalImage);

    const modalName = document.createElement('h3');
    modalName.textContent = data.name.first;
    modalName.classList.add('modal-name');
    modalInfoCotainer.appendChild(modalName);

    const modalEmail = document.createElement('p');
    modalEmail.classList.add('modal-text');
    modalEmail.textContent = data.email;
    modalInfoCotainer.appendChild(modalEmail);

    const modalCity = document.createElement('p');
    modalCity.classList.add('modal-text');
    modalCity.textContent = data.location.city;
    modalInfoCotainer.appendChild(modalCity);

    const hr = document.createElement('hr');
    modalInfoCotainer.appendChild(hr);

    const modalNumber = document.createElement('p');
    modalNumber.classList.add('modal-text');
    modalNumber.textContent = data.cell;
    modalInfoCotainer.appendChild(modalNumber);

    const modalAddress = document.createElement('p');
    modalAddress.classList.add('modal-text');
    modalAddress.textContent = data.location.state + ' ' + data.location.country + ' ' + data.location.postcode;
    modalInfoCotainer.appendChild(modalAddress);

    const modalBirthday = document.createElement('p');
    modalBirthday.classList.add('modal-text');
    modalBirthday.textContent = 'Birthday ' + data.dob.date;
    modalInfoCotainer.appendChild(modalBirthday);
  })

}
/* ===================================== 
   Public API Request
======================================== */

@import url('https://fonts.googleapis.com/css?family=Nunito');

* {
	box-sizing: border-box;
}

html, body {
    width: 100%;
    max-width: 100%;
}

body {
    font-family: "Nunito", sans-serif;
    text-align: center;
    background: rgba(235, 235, 235, 0.9);
}

header {
    padding: 15px 5px 5px;
}

.header-inner-container {
    max-width: 1180px;
    margin: auto;
}

header h1 {
    font-size: 1.25em;
    color: rgba(50, 50, 50, 0.9);
    margin-top: 35px;
}

.search-input {
    padding: 0.4rem 1rem;
    border: 1px solid rgba(200, 200, 200, 0.9);
    border-radius: 0.25rem 0 0 0.25rem ;
    max-width: 20rem;
    transition: .4s ease-out;
    outline: none;
}

.search-input:active, .search-input:hover, .search-input:focus {
    border: 1px solid rgba(50, 50, 50, 0.9);
}

.search-submit {
    cursor: pointer;
    height: 33px;
    background: rgba(245, 245, 245, 0.9);
    border-radius: 0 0.25rem 0.25rem 0;
    border: 1px solid rgba(200, 200, 200, 0.9);
    transition: .4s ease-out;
    outline: none;
}

.search-submit:active, .search-submit:hover, .search-submit:focus {
    background: rgba(255, 255, 255, 0.9);
    border: 1px solid rgba(50, 50, 50, 0.9);
}


/* ===================================== 
   Gallery
======================================== */

.gallery {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-evenly;
    width: 100%;
    max-width: 1200px;
    margin: auto;
}
  
.card {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: flex-start;
    cursor: pointer;
    width: 100%;
    max-width: 360px;
    margin: 10px 10px 20px;
    padding: 10px;
    background: rgba(245, 245, 245, 0.9);
    border-radius: 0.25em;
    border: 1px solid rgba(50, 50, 50, 0.3);
    transition: .4s ease-out;
    overflow: hidden;
}

.card-img {
    width: 95px;
    margin: 10px 15px auto 10px;
    border-radius: 50%;
}

.card-info-container {
    text-align: left;
}

.card-name {
    margin: 20px auto 0;
}

.card-text {
    font-size: 0.9em;
    color: rgba(50, 50, 50, 0.7);
    margin: 7px auto;
    transition: .4s ease-out;
}

.cap {
    text-transform: capitalize;
}


/* ===================================== 
   Modal
======================================== */

.modal-container {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.7);
}

.modal {
    position: relative;
    width: 95%;
    max-width: 420px;
    min-height: 415px;
    margin: 10px auto auto;
    padding-bottom: 15px;
    background: rgba(255, 255, 255, 1);
    border-radius: 0.25em;
    border: 1px solid rgba(100, 100, 100, 0.3);
    transition: .4s ease-out;
}

.modal-close-btn {
    position: absolute;
    top: 15px;
    right: 15px;
    cursor: pointer;
    color: rgba(255, 255, 255, 0.9);
    background: rgba(0, 0, 0, 0.8);
    outline: none;
    border-radius: 0.25em;
    border: 1px solid rgba(50, 50, 50, 0.3);
}

.modal-img {
    width: 150px;
    margin-top: 35px;
    border-radius: 50%;
}

.modal-name {
    margin-bottom: 5px;
}

.modal-text {
    color: rgba(50, 50, 50, 0.7);
    margin: 10px;
}

.modal hr {
    width: 75%;
    margin: 25px auto 30px;
    border-color: rgba(200, 200, 200, 0.2);
}

.modal-btn-container {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: space-evenly;
    width: 95%;
    max-width: 420px;
    padding: 10px 15px 15px;;
    margin: 10px auto auto;
    background: rgba(255, 255, 255, 1);
    border-radius: 0.25em;
    border: 1px solid rgba(100, 100, 100, 0.3);
}


.modal-btn-container .btn {
    display: inline-block;
    cursor: pointer;
    font-size: 0.85em;
    text-transform: uppercase;
    color: rgba(255, 255, 255, 0.9);
    padding: 0.75em 1.5em;
    background: rgba(0, 0, 0, 0.8);
    border-radius: 0.35em;
    transition: .4s ease-out;
    outline: none;
  }
  

/* ===================================== 
   Media Queries
======================================== */

/* ===================================== 
   Tablet
======================================== */

@media (min-width: 768px) {
    .header-inner-container {
        display: flex;
        flex-direction: row;
        flex-wrap: nowrap;
        justify-content: space-between;
        padding-right: 25px;
        padding-left: 25px;
    }

    .header-text-container {
        text-align: left;
    }

    .search-container {
        margin-top: 25px;
    }

    .modal {
        margin-top: 100px;
    }
}


/* ===================================== 
   Desktop
   Hover styles on desktop 
======================================== */

@media (min-width: 1024px) {

    .card:hover {
        background: rgba(255, 255, 255, 1);
        border: 1px solid rgba(50, 50, 50, 0.9);
    }

    .card:hover .card-text {
        color: rgba(25, 25, 25, 1); 
    }

    .btn:hover {
        background: rgba(255, 255, 255, 1);
        color: rgba(25, 25, 25, 1); 
    }
}
<!DOCTYPE html>
<html lang="en-US">
    <head>
        <title>Public API Requests</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <link href="css/normalize.css" rel="stylesheet">
        <link href="css/styles.css" rel="stylesheet">
    </head>
    <body>

        <!-- =======================
            Gallery container
        ======================== -->
        <header>
            <div class="header-inner-container">
                <div class="header-text-container">
                    <h1>AWESOME STARTUP EMPLOYEE DIRECTORY</h1>
                </div>

                <div class="search-container">
                    <!-- ======================
                        Search markup:
                        You can use the commented out markup below as a template
                        for your search feature, but you must use JS to create and
                        append it to `search-container` div.
                        IMPORTANT: Altering the arrangement of the markup and the
                        attributes used may break the styles or functionality.
                        <form action="#" method="get">
                            <input type="search" id="search-input" class="search-input" placeholder="Search...">
                            <input type="submit" value="&#x1F50D;" id="search-submit" class="search-submit">
                        </form>
                    ======================= -->
                </div>
            </div>
        </header>

        <div id="gallery" class="gallery">
            <!-- ======================
                Gallery markup:
                You can use the commented out markup below as a template
                for each of your Gallery items, but you must use JS to
                create and append them to the `gallery` div.
                IMPORTANT: Altering the arrangement of the markup and the
                attributes used may break the styles or functionality.
                <div class="card">
                    <div class="card-img-container">
                        <img class="card-img" src="https://placehold.it/90x90" alt="profile picture">
                    </div>
                    <div class="card-info-container">
                        <h3 id="name" class="card-name cap">first last</h3>
                        <p class="card-text">email</p>
                        <p class="card-text cap">city, state</p>
                    </div>
                </div>
            ======================= -->
        </div>

        <!-- =======================
            Modal markup:
            You can use the commented out markup below as a template
            for your modal, but you must use JS to create and append
            it to `body`.
            IMPORTANT: Altering the arrangement of the markup and the
            attributes used may break the styles or functionality.
            <div class="modal-container">
                <div class="modal">
                    <button type="button" id="modal-close-btn" class="modal-close-btn"><strong>X</strong></button>
                    <div class="modal-info-container">
                        <img class="modal-img" src="https://placehold.it/125x125" alt="profile picture">
                        <h3 id="name" class="modal-name cap">name</h3>
                        <p class="modal-text">email</p>
                        <p class="modal-text cap">city</p>
                        <hr>
                        <p class="modal-text">(555) 555-5555</p>
                        <p class="modal-text">123 Portland Ave., Portland, OR 97204</p>
                        <p class="modal-text">Birthday: 10/21/2015</p>
                    </div>
                </div>
                // IMPORTANT: Below is only for exceeds tasks
                <div class="modal-btn-container">
                    <button type="button" id="modal-prev" class="modal-prev btn">Prev</button>
                    <button type="button" id="modal-next" class="modal-next btn">Next</button>
                </div>
            </div>
        ======================== -->

        <!-- Add your JS here -->
        <script src="js/app.js" charset="utf-8"></script>

    </body>
</html>
...