Jquery Event Click does not work in image preview

1

Clicking on the img element does not work to call a JS function, what am I doing wrong?

Follow the code below:

HTML:

<label class="control-label">Select File</label>
<input id="input-id" type="file" class="file">

JS:

$("#input-id").fileinput({
  showZoom: true,
  zoomIcon: false
});

//Tentativa 1
$("img[class='kv-preview-data file-preview-image']").on('click', function() {
  alert('addMore click event');
});

//Tentativa 2
$("img[class='kv-preview-data file-preview-image']").click(function() {
  alert( "Handler for .click() called." );
});

//Tentativa 3
$(document).ready(function() {
  $("img[class='kv-preview-data file-preview-image']").click(function () {
    alert("Hello!");
  });
});

//Tentativa 4
$(".kv-file-content").on('click', function() {
  alert('addMore click event');
});

None of the 4 attempts do not work. Here's an example JSFIDDLE .

Here's the image to click on:

Any solution?

    
asked by anonymous 19.02.2017 / 06:03

1 answer

1
$(".file-preview").on('click', "img[class='kv-preview-data file-preview-image']", function() {
  alert('addMore click event');
});

You have to delegate this event since this image does not yet exist when running jQuery. As you are doing jQuery searches for img[class='kv-preview-data file-preview-image'] , it does not find and does not add anything.

Using $(algoExistente).on(evento, delegado, function(){ it will search the delegado at the time of the click within algoExistente .

jsFiddle: link

    
19.02.2017 / 06:44