Reputation: 169
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.
Upvotes: 4
Views: 31359
Reputation: 485
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>
Upvotes: 5
Reputation: 195952
You are creating elements with jquery.. so just use its methods
$("<img>")
.attr("src", item.preview.medium)
.click(function(){ showStream(index);})
.appendTo("#images");
Or you use this syntax instead
$("<img>", {
src: item.preview.medium,
click: function(){showStream(index);}
}).appendTo("#images");
Upvotes: 2
Reputation: 892
Try this way;
<script type="text/javascript">
$.getJSON("https://api.twitch.tv/kraken/search/streams?q=star&type=suggest&callback=?", function (data) {
$.each(data.streams, function (index, item) {
$("<img>").attr("src", item.preview.medium).appendTo("#images");
});
});
$("#images img").on("click",function(e){
alert("your function all")
})
</script>
Upvotes: 1
Reputation: 4967
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 :)
Upvotes: 5
Reputation: 4167
The function name after on click is blank?
$("#something").attr("onClick","new_function()");
Upvotes: 0