Vityata
Vityata

Reputation: 43595

Append mouseover event to img in a div with jQuery

I am trying to append a mouseover event to an image in a div with jQuery. Here is how I append the imgs to the div. This is my code, appending the img and the href to the div. Now, I want the mouseover. So far I have tried a lot of things, which simply did not work, like trying to append a function ...

for (var index in obj){                 
    $("#my_div").append($("<a>", 
    {
        href: urlSite, 
        html: $("<img>", { src: avatar }),
    }));
}

Upvotes: 0

Views: 855

Answers (1)

Ryuu
Ryuu

Reputation: 606

You can use the jquery on function to add handlers to events like so

$('#your_image_id').on('mouseover', function() {
    console.log('hello');
});

Edit

To do it dynamically:

$('#my_div').append($('<img>').attr('src', avatar).on('mouseover', function() {
    console.log('hello');
}));

Edit2

for (var index in obj){                 
    $("#my_div").append($("<a>", 
    {
        href: urlSite, 
        html: $("<img>", { src: avatar }),
    }).mouseover(function() {
        $('#my_other_div').append($(this).attr('href')); 
    })); 
}

Upvotes: 1

Related Questions