Search code examples
jqueryhtmlajaxfadetoinstagram-api

jQuery fadeTo not working with an img tag that's placed in the same script tag


Okay i am using the instagram's API to retrieve profile images and usernames. Moreover, i want the profile images to fade when the mouse hovers over it. However, that doesn't seem to work and I'm not sure if it's because the img is placed inside the script tag. I've been looking for hours for an answer but i couldn't find any. So i'd really appreciate it if someone helped me.

<script>


        $(document).ready(function () {



               $('#images').hover(function () {
                    $(".img").fadeTo("fast",0.5);
                }, function () {
                     $(".img").fadeTo("fast",1);
                });


            $("input").keypress(function (event) {

                if (event.which === 13) {
                    event.preventDefault();

                    $("#images").empty();
                    $.ajax({
                        type: 'GET',
                        url: 'get_info.php',
                        data: {keyword: $("input").val()},
                        dataType: 'JSON',
                        success:
                                function (jsonStr) {
                                    $.each(jsonStr.data, function (index, element) {


                                        $('#images').append("<div class='instaUser'><img  class='img' src=" + element.profile_picture + " /><span class='username'>@" + element.username + "</span></div>");

                                    });
                                }

                    });
                }
            });
        });

    </script>

Solution

  • Your image is dynamically added to the DOM, so you have to use event delegation. However, .hover doesn't have delegation by itself since it's a shortcut to mouseenter and mouseleave. Use those events for delegation:

    $('#images').on({
        mouseenter : function(){
            $(this).fadeTo("fast",0.5);
        },
        mouseleave : function(){
            $(this).fadeTo("fast",1);
        }
    }, '#img');
    

    Please, take note that you are appending multiple elements with the same ID. IDs must be unique, use classes instead.

    Read about the event delegation here.