Search code examples
javascriptgiphy-api

Where can I add a second on click function that targets the var "giphyImage"?


I have tried: inside the for loop, inside the .done function but outside the for loop, and before and after the button function end. I'm wanting to be able to run a function on the click of the giphyImage.

Below is the code I am trying to insert somewhere to get the second click and test it in the console but nothing displays in the console at all.

$('giphyImage').on('click', function() {
    console.log('testclickedimage')
});

Here is my HTML:

<!-- language: lang-html -->
<!DOCTYPE html>
<html>

<head>
<!--Megatags-->
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--Title on browser tab-->
<title>Bradley's Giphy API App</title>
<!--Reset tag-->
<link rel="stylesheet" href="assets/css/reset.css">
<!--Bootstrap tag-->
<link          href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!--Css tag (after bootstrap)-->
<link rel="stylesheet" href="assets/css/style.css">
</head>

<body>
<div class="container">
    <div class="buttons">
        <button data-giphy="cat">Cats</button>
        <button data-giphy="dog">Dogs</button>
        <button data-giphy="bird">Birds</button>
        <button data-giphy="horse">Horses</button>
        <button data-giphy="parrots">Parrots</button>
        <button data-giphy="jason schwartzman">Jason Schwartzman</button>
        <button data-giphy="zooey deschanel">Zooey Deschanel</button>
        <button data-giphy="michael cera">Michael Cera</button>
        <button data-giphy="zach braff">Zach Braff</button>
        <button data-giphy="natalie portman">Natalie Portman</button>
        <button data-giphy="pizza">Pizza</button>
        <button data-giphy="hamburger">Hamburger</button>
        <button data-giphy="beer">Beer</button>
        <button data-giphy="shrimp">Shimp</button>
        <button data-giphy="lobster">Lobster</button>
    </div>
    <div class="addButtons"></div>
    <div class="gifsAppearHere"></div>
</div>
<!--Jquery tag-->
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
<!--Javascript tag-->
<script src="assets/javascript/game.js"></script>
</body>

</html>

Here is my javascript code:

$('button').on('click', function() {
    var giphy = $(this).data('giphy');
    var queryURL = "http://api.giphy.com/v1/gifs/search?q=" + giphy 
                   + "&api_key=dc6zaTOxFJmzC&limit=10";
    //testing variable
    console.log (queryURL);

    $.ajax({
        url: queryURL,
        method: 'GET'
    }).done(function(response) {  //done function
        //console logs results remove when done testing
        console.log(response)
        //pulls response from data key
        var results = response.data
        //loops though images randomly
        for (var i = 0; i < results.length; i++) {
            //creates Div
            var giphyDiv = $('<div class="giphyDiv">');
            //pulls ratings
            var p = $('<p>').text('Ratings: ' + results[i].rating);
            //creats images
            var giphyImage = $('<img>');
            //pulls images from API
            giphyImage.attr('src', results[i].images.fixed_height.url);
            //appends rating and image
            giphyDiv.append(p);
            giphyDiv.append(giphyImage);
            //prepends to class specified in html
            $('.gifsAppearHere').prepend(giphyDiv);
        } //end of for loop
    }); //end of done function
}); //end of button function

::edit:: was able to fix by targeting 'img' instead of 'giphyImage'

$('img').on('click', function() {
console.log('testclickedimage')
});

now console displays 'testclickedimage'


Solution

  • I think your problem is that giphyImage is a string and not a DOM element. That's why you cannot attach an event listener to it.

    Try this:

    var giphyImage = document.createElement('img');
    giphyImage.setAttribute('src', yourImageSource);
    giphyImage.addEventListener('click', yourFunctionHere /* without () */);
    
    giphyDiv.appendChild(giphyImage);
    

    Edit

    A better way to achieve the same result is to use event delegation.

    In short, instead of attaching one event listener to each image element, you can simply attach a single event listener to a parent element, which will fire for all children matching some criteria (for example, a class name). Even better, it does not matter at all if the child already exists or is added at a later time.

    Example using pure JavaScript:

    var body = document.querySelector('body');
    
    body.addEventListener('click', function(event) {
      if (event.target.tagName === 'IMG')
        youFunctionHere();
    })