1

at the moment I try to apply some jquery to html elements I created before with js. But it doesn't work.

This code works, so the reason can't be that I forgot something to import:

$(document).ready(function(){
    $(".test").click(function(){
        $(this).css("border", "5px solid #000");
    }); });
.test{
  width:100px;
  height:100px;
  background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">

</div>

But if I try the same on html I creat with js nothing happens:

document.getElementById('files').addEventListener('change', handleFileSelect, false);

  function handleFileSelect(evt) {
    var files = evt.target.files;

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var span = document.createElement('span');
          span.innerHTML = 
          [
            '<img src="', 
            e.target.result,
            '" title="', escape(theFile.name), 
            '"/>'
          ].join('');
          
          document.getElementById('list').insertBefore(span, null);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }

$(document).ready(function(){  
  $("img").on("click", function(){
    $(this).css("border", "5px solid #000");
});});
//$(document).ready(function(){
//    $("img").click(function(){
//        $(this).css("border", "5px solid #000");
//    }); });
img{
  height: 75px;
  border: 1px solid #000;
  margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='test-form'>
  <input type="file" id="files" name='input1' multiple/><br>
  <output id="list"></output><br>
</form>

I thought maybe the function .on() can help me but it doesn't work either.

But "Event handlers attached using the on() method will work for both current and FUTURE elements (like a new element created by a script)" is from W3C schools, even if this is not the best reference.

So what do I wrong, and where is my mistake? I tried to apply classes and and did some other stuff to get it working, but nothing solved my problem.

Probalby its because the created new element in my opinion. Any hints and improvements are very welcome, thank you.

user576892
  • 46
  • 7

0 Answers0