Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery onClick Image Event

I'm trying to make it so when you click on an image, it will do a function inside the document.

Now I am having a bit of trouble and I'm sure this is some stupid mistake but whats wrong here?

<script type="text/javascript">
$.getJSON("https://api.twitch.tv/kraken/search/streams?q=star&type=suggest&callback=?", function (data) {
    $i = 0;
    $.each(data.streams, function (index, item) {
        $("<img>").attr("src", item.preview.medium).attr("onclick", "").appendTo("#images");
        $i++;
    });
});
</script>

They display correctly, its just that the onclick event doesn't work.

like image 215
user3023566 Avatar asked Oct 27 '25 04:10

user3023566


2 Answers

Give each of your image a class, like 'leImage'.

Create an event listener like this:

$(".leImage").on("click", function()
{
    // Do stuff, get id of image perhaps?
    var id = this.id;
    // or
    var id = $(this).attr("id");
});

If this is not what you're asking for then you'll have to be more clear :)

like image 121
Jonast92 Avatar answered Oct 29 '25 19:10

Jonast92


First of all set id for image.

<img src="../images/warning.png" id="imageId"/>

After that use this code:

<script>
    $('#imageId').click(function () {
        alert('It works!');
    });
</script>
like image 23
Dmitry Nichiporenko Avatar answered Oct 29 '25 17:10

Dmitry Nichiporenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!