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>
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 tomouseenter
andmouseleave
. Use those events for delegation: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.