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(";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.
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.
Share Improve this question asked Nov 28, 2013 at 23:03 user3023566user3023566 1691 gold badge1 silver badge12 bronze badges5 Answers
Reset to default 5Give 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 :)
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>
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");
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>
The function name after on click is blank?
$("#something").attr("onClick","new_function()");