0

The search input field creates a button from the user text using .createElement. That button is prepended identical to the other HTML buttons. Clicking the button fires a function that gets JSON search parameters from the .innerHTML of the button clicked. Why is my JSON function not able to recognize this new button?

HTML
<!DOCTYPE html>
    <html lang="en-us">
      <head>
        <title>Giphy API</title>
        <meta charset="utf-8" />
        <meta name="description" content="Giphy API" />
        <meta name="keywords" content="javascript, api, web developement" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <link
          rel="stylesheet"
          href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
          integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
          crossorigin="anonymous"
        />
      </head>
      <body>
        <div class="container">
          <form id="button-form row">
            <label for="button-input"></label>
            <input type="text" id="button-input" />
            <input id="add-button" type="submit" value="Search Giphy" />
          </form>
        </div>
        <div class="container">
          <div class="col">
            <button class="gif-button">dogs</button>
            <button class="gif-button">cats</button>
            <button class="gif-button">birds</button>
          </div>
        </div>

        <div class="container gifs">
          <div class="images row"></div>
        </div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script type="text/javascript" src="assets/javascript/script.js"></script>
      </body>
    </html>
Javascript
let gifButton = document.querySelector(".gif-button").innerHTML;
let search = document.getElementById("button-input");

//       ******* SEARCH GIFS *******
$("#add-button").on("click", function() {
  event.preventDefault();
  //on click create button from input text
  var newButton = document.createElement("button");
  newButton.innerHTML = search.value;
  newButton.setAttribute("class", "gif-button");
  $(".col").prepend(newButton);
});

//       ******* CREATE GIFS *******
// Event listener for our gif-button
$(".gif-button").on("click", function() {
  // Storing our giphy API URL for random images
  let selection = this.innerHTML;
  let queryURL =
    "https://api.giphy.com/v1/gifs/random?api_key=BkaUZZWcFij6J7AoQj3WtPb1R2p9O6V9&tag=" +
    selection;

  // Perfoming an AJAX GET request to our queryURL
  $.ajax({
    url: queryURL,
    method: "GET"
  })

    // After the data from the AJAX request comes back
    .then(function(response) {
      // Saving the image_original_url property
      var imageUrl = response.data.images.fixed_height.url;

      // Creating and storing an image tag
      var image = $("<img>" + "</br>" + "</br>");

      // Setting the Image src attribute to imageUrl
      image.attr("src", imageUrl);
      image.attr("alt", gifButton);
      image.attr("class", "gif");
      image.attr("data-state", "still");
      image.attr("data-still", response.data.images.fixed_height_still.url);
      image.attr("data-animate", response.data.images.fixed_height.url);

      // Prepending the image to the images div
      $(".images").prepend(image);
    });

  //animate on click
  $(".images").on("click", function() {
    console.log("click");
    // The attr jQuery method allows us to get or set the
    // value of any attribute on our HTML element
    var state = $(".gif").attr("data-state");

    if (state === "still") {
      // If the clicked image's state is still,
      // update its src attribute to what its data-animate value is.
      // Then, set the image's data-state to animate
      $(".gif").attr("src", $(".gif").attr("data-animate"));
      $(".gif").attr("data-state", "animate");
      console.log("animate");
    } else {
      // Else set src to the data-still value
      $(".gif").attr("src", $(".gif").attr("data-still"));
      $(".gif").attr("data-state", "still");
      console.log("still");
    }
  });
});
XtraChase
  • 1
  • 2

1 Answers1

0

By default, .on( events, handler ) does not work for dynamically created elements.

Base on this question and answer, you can use $(PARENT SELECTOR).on( events, SELECTOR, handler) to solve the problem. In your code, it can be $(".col").on("click", ".gif-button", function() { ... });.

Here is the complete codeļ¼š

let gifButton = document.querySelector(".gif-button").innerHTML;
let search = document.getElementById("button-input");

//       ******* SEARCH GIFS *******
$("#add-button").on("click", function() {
  event.preventDefault();
  //on click create button from input text
  var newButton = document.createElement("button");
  newButton.innerHTML = search.value;
  newButton.setAttribute("class", "gif-button");
  $(".col").prepend(newButton);
});

//       ******* CREATE GIFS *******
// Event listener for our gif-button
$(".col").on("click", ".gif-button", function() {
  // Storing our giphy API URL for random images
  let selection = this.innerHTML;
  let queryURL =
    "https://api.giphy.com/v1/gifs/random?api_key=BkaUZZWcFij6J7AoQj3WtPb1R2p9O6V9&tag=" +
    selection;

  // Perfoming an AJAX GET request to our queryURL
  $.ajax({
    url: queryURL,
    method: "GET"
  })

    // After the data from the AJAX request comes back
    .then(function(response) {
      // Saving the image_original_url property
      var imageUrl = response.data.images.fixed_height.url;

      // Creating and storing an image tag
      var image = $("<img>" + "</br>" + "</br>");

      // Setting the Image src attribute to imageUrl
      image.attr("src", imageUrl);
      image.attr("alt", gifButton);
      image.attr("class", "gif");
      image.attr("data-state", "still");
      image.attr("data-still", response.data.images.fixed_height_still.url);
      image.attr("data-animate", response.data.images.fixed_height.url);

      // Prepending the image to the images div
      $(".images").prepend(image);
    });

  //animate on click
  $(".images").on("click", function() {
    console.log("click");
    // The attr jQuery method allows us to get or set the
    // value of any attribute on our HTML element
    var state = $(".gif").attr("data-state");

    if (state === "still") {
      // If the clicked image's state is still,
      // update its src attribute to what its data-animate value is.
      // Then, set the image's data-state to animate
      $(".gif").attr("src", $(".gif").attr("data-animate"));
      $(".gif").attr("data-state", "animate");
      console.log("animate");
    } else {
      // Else set src to the data-still value
      $(".gif").attr("src", $(".gif").attr("data-still"));
      $(".gif").attr("data-state", "still");
      console.log("still");
    }
  });
});
<!DOCTYPE html>
    <html lang="en-us">
      <head>
        <title>Giphy API</title>
        <meta charset="utf-8" />
        <meta name="description" content="Giphy API" />
        <meta name="keywords" content="javascript, api, web developement" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <link
          rel="stylesheet"
          href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
          integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
          crossorigin="anonymous"
        />
      </head>
      <body>
        <div class="container">
          <form id="button-form row">
            <label for="button-input"></label>
            <input type="text" id="button-input" />
            <input id="add-button" type="submit" value="Search Giphy" />
          </form>
        </div>
        <div class="container">
          <div class="col">
            <button class="gif-button">dogs</button>
            <button class="gif-button">cats</button>
            <button class="gif-button">birds</button>
          </div>
        </div>

        <div class="container gifs">
          <div class="images row"></div>
        </div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      </body>
  <html>
iLtc
  • 74
  • 1
  • 5