I have a html and jQuery code in which there are two img
dynamically created and after ajax I'm applying click events on the images but the click events not working. Means they show nothing. that the imae is clicked or not. I'm showing my code following:-
<div id="images">
<img id="image/5c07a4337c76881db6bf9a7f" src="data:image/jpeg;base64,/9j/4AA.....>
<img id="image/5c07a4337c76881db6bf9a7d" src="data:image/jpeg;base64,/9j/4AA.....>
</div>
$( document ).ready(function() {
$.ajax({
url: "/api/v1/get-all-upload-image?sortBy=date",
type: "GET",
success: function(response){
console.log(response);
$.ajax({
url : "/api/v1/base-strings",
type:"GET",
success:function(response){
console.log(response.response.data)
for (i= 0; i < response.response.data.length; i++){
console.log(response.response.data[i])
var base64_string = response.response.data[i].data;
var img = document.createElement("img");
img.setAttribute("id", "image/"+response.response.data[i].files_id);
img.setAttribute("onclick", "addListeners()");
// added `width` , `height` properties to `img` attributes
img.style.width ='340px';
img.style.height ='194px';
img.style.margin = '50px';
img.style.cursor = 'pointer';
img.src = "data:image/jpeg;base64," + base64_string;
var preview = document.getElementById("images");
preview.appendChild(img);
}
}
});
}
});
function addListeners () {
$('img[id^="image"]').on('click', function(){
var val = $(this).attr('id').split('/');
id= val[val.length - 1]
});
}
$('img[id^="image"]').click(function(){
alert("hello")
})
$('img[id^="image"]').on('click', function(){
var val = $(this).attr('id').split('/');
id= val[val.length - 1]
});
});
Error
Uncaught ReferenceError: addListeners is not defined at HTMLImageElement.onclick
What is the problem with the code why it is not working?