0

So I have made an ajax request that returns random images

enter image description here

this is my ajax request

$.ajax({
  url: 'https://randomuser.me/api/?nat=us&results=12&',
  dataType: 'json',
  success: function(data) {
    console.log(data); //this should log the data for 12 employees in JSON format



    var employeeInfo = data.results //creating a reference to data.results
    var _cardTemplate = ''; //make variable reference for gallery
    var modalBoxContainer = ''; //make variable for modal containers
    $.each(employeeInfo, function(index, employee) {
      //create variable references for Name, email, city,state, etc
      var name = employee.name.first + " " + employee.name.last;
      var email = employee.email;
      var picture = employee.picture.large;
      var location = employee.location.city;
      var number = employee.phone;
      var fullStreet = employee.location.street + " " + location + " " + employee.location.postcode;
      var birthday = employee.dob.date;

      //CREATE GALLERY CARDS AND SHOW CONTENT FOR SMALL GALLERY CARDS


      _cardTemplate += '<div class="card">';
      _cardTemplate += '<div class="card-img-container">';
      _cardTemplate += '<img class="card-img" src= "' + picture + '" alt="profile picture"></div>';
      _cardTemplate += '<div class="card-info-container"><h3 id="name" class="card-name cap">' + name + '</h3>';
      _cardTemplate += '<p class="card-text">' + email + '</p><p class="card-text cap">' + location + '</p>';
      _cardTemplate += '</div></div>';



      //CREATE MODAL CARDS AND SHOW CONTENT FOR THEM

      modalBoxContainer += '<div class="modal-container">';
      modalBoxContainer += '<div class="modal">';
      modalBoxContainer += '<button type="button" id="modal-close-btn" class="modal-close-btn"><strong>X</strong></button>';
      modalBoxContainer += '<div class="modal-info-container"><img class="modal-img" src= "' + picture + '" alt="profile picture"><h3 id="name" class="modal-name cap">' + name + '</h3><p class="modal-text">' + email + '</p><p class="modal-text cap">' + location + '</p>';
      modalBoxContainer += '<hr>';
      modalBoxContainer += '<p class="modal-text">' + number + '</p><p class="modal-text">' + fullStreet + '</p><p class="modal-text">' + birthday + '</p></div>';
      modalBoxContainer += '<div2>';


      /*appends an "active" class to .modal(pop-up-window) and .modal-container(overlay) when .card is clicked

   I used a code snippet from https://www.pair.com/support/kb/how-to-use-jquery-to-generate-modal-pop-up-when-clicked/
   */
      $(document).ready(function() { //this makes sure the function will run only after the elements are fully loaded

        $('.card').on("click", function() {
          //$(".modal, .modal-container").addClass("active");
          $(".modal, .modal-container").addClass("active");
          console.log('the modal should pop up after clicking the div card')
        });

        /*This removes the "active" class to .modal(pop-up-window)  and .modal-container 
        when clicking on: the "X" button, the opened modal or clicking outside the modal,
        so the user has 3 ways to close a modal, this improves UX
        */

        $('#modal-close-btn, .modal, .modal-container').on("click", function() {
          $(".modal, .modal-container").removeClass("active");
          console.log('you clicked on the x button');
        });
      })
    });

    $('#gallery').append(_cardTemplate); //Append Finally all cards with employee details
    //Finally, I will append modalBoxContainer inside body tag
    $('body').append(modalBoxContainer);
  }

})

I added event listeners to $('.card')which are the 12 cards in order to display $(".modal, .modal-container") these are modals and an over lay, I end up with having the same modal no matter which picture I click on , can someone help me so that I can see modals that match the same info for each small gallery

imjared
  • 19,492
  • 4
  • 49
  • 72
Erik L
  • 195
  • 1
  • 2
  • 18
  • try this `$(this).removeClass("active"); ` inside your `click` – Bibberty Dec 24 '18 at 19:39
  • I tried that but it unfortunately it didn't work – Erik L Dec 24 '18 at 19:42
  • It seems like you have just one container for all modals. I would expect you would want as many as the employees. – N Sarj Dec 24 '18 at 19:59
  • Ok, I have looked through code. the `$(document).ready()` should be on the outside of this in my view.Take a look at the script on this Repl. It is a rejig of what you are doing. Please understand I cannot test it as it relies on ajax call . I recommend you separate that out so you can use test data first to get page build and formatting working first : https://repl.it/@PaulThomas1/WirySnivelingDatum – Bibberty Dec 24 '18 at 20:11
  • Don't call `$(".card").on("click")` inside a loop. Each time you do that, you're adding another event handler to all the cards created in previous iterations. – Barmar Dec 24 '18 at 20:11
  • The event handler needs to use DOM navigation relative to `$(this)` to operate just on the card you clicked on. And see https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements for the simplest way to add handlers on elements added with AJAX. – Barmar Dec 24 '18 at 20:14
  • @NSarj but wouldn’t using clone() 12 times basically repeat every picture again, I’m a new programmer – Erik L Dec 24 '18 at 20:42
  • @ErikL, take a look at my reply and ask for any clarifications or elaboration. – N Sarj Dec 24 '18 at 20:58
  • Erik - Take a look at the Repl now. It works as intended for the UI based on sample data. Now you just need to add an ajax data feed and styling (mine looks horrible). https://repl.it/@PaulThomas1/WirySnivelingDatum ignore the `script.js` file as this is the old code. Look at the ones residing in scripts – Bibberty Dec 24 '18 at 20:59
  • @Paul Thomas ok I'll take a look t it – Erik L Dec 24 '18 at 21:01

1 Answers1

1

I am providing general guidelines and a code outline. Feel free to ask for clarifications.

The code I am writing is neither complete or efficient, but it should serve as a starting point.

You need to keep a correlation between the card you click and the modal you want to open.

You're not doing that right now.

You can use jQuery's data capability (https://api.jquery.com/data/) to do that or a normal id.

First, add a index data property on each card template or build an id for that template. You have the index from the $.each

Then create a separate div for each modal. Each div should have a corresponding index with the respective card.

You add a click handler on all cards, where you only make active the modal that corresponds to it.

$.ajax({
    url: 'https://randomuser.me/api/?nat=us&results=12&',
    dataType: 'json',
    success: function(data) {
    console.log(data); //this should log the data for 12 employees in JSON format

    var employeeInfo = data.results //creating a reference to data.results
    var _cardTemplate = ''; //make variable reference for gallery
    //start the container outside the loop:
    var modalBoxContainer = '<div class="modal-container">'; 
    $.each(employeeInfo, function(index, employee) {
        //create variable references for Name, email, city,state, etc
        var name = employee.name.first + " " + employee.name.last;
        var email = employee.email;
        var picture = employee.picture.large;
        var location = employee.location.city;
        var number = employee.phone;
        var fullStreet = employee.location.street + " " + location + " " + employee.location.postcode;
        var birthday = employee.dob.date;

        _cardTemplate += '<div class="card" data-index="'+index+'">';
        _cardTemplate += '<div class="card-img-container">';
        _cardTemplate += '<img class="card-img" src= "' + picture + '" alt="profile picture"></div>';
        _cardTemplate += '<div class="card-info-container"><h3 id="name" class="card-name cap">' + name + '</h3>';
        _cardTemplate += '<p class="card-text">' + email + '</p><p class="card-text cap">' + location + '</p>';
        _cardTemplate += '</div></div>';

        //add each 
        modalBoxContainer += '<div class="modal" data-index="'+index+'">';
        modalBoxContainer += '<button type="button" id="modal-close-btn" class="modal-close-btn"><strong>X</strong></button>';
        modalBoxContainer += '<div class="modal-info-container"><img class="modal-img" src= "' + picture + '" alt="profile picture"><h3 id="name" class="modal-name cap">' + name + '</h3><p class="modal-text">' + email + '</p><p class="modal-text cap">' + location + '</p>';
        modalBoxContainer += '<hr>';
        modalBoxContainer += '<p class="modal-text">' + number + '</p><p class="modal-text">' + fullStreet + '</p><p class="modal-text">' + birthday + '</p></div>';
    });
    //close container:
    modalBoxContainer += "</div>";

    $(document).ready(function() { //this makes sure the function will run only after the elements are fully loaded

        $('.card').on("click", function() {
            var theIndex = $(this).data("index");

            $(".modal", $(".modal-container")).each(function(index){
                if( $(this).data("index") === theIndex) $(this).addClass("active");
                else $(this).removeClass("active");
            });
        });

        $('#modal-close-btn, .modal, .modal-container').on("click", function() {
            $(".modal", $(".modal-container")).removeClass("active");
            console.log('you clicked on the x button');
        });
     })



     $('#gallery').append(_cardTemplate); //Append Finally all cards with employee details
     //Finally, I will append modalBoxContainer inside body tag
     $('body').append(modalBoxContainer);
    }

})
N Sarj
  • 374
  • 3
  • 11
  • Hi, so this worked in getting the matching data modal upon clicking on a gallery card, but I also somehow ended up getting 24 gallery cards, twice as much as I had before – Erik L Dec 25 '18 at 03:08
  • 1
    Great! Happy I could help. – N Sarj Dec 25 '18 at 10:01