0

I have a list with a images. When i click the image i want to highlight it. I also have a upload new image button, which uploads in list a new image. But when i click the uploaded images they don't highlight. This is the code in snippet.

function changePhoto(input) {
  if (input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
      var source = e.target.result;
      $(".list").append("<li><img src=" + source + " class='image'></li>")
    }
    reader.readAsDataURL(input.files[0]);
  }
}

$("#addPhoto").change(function() {
  changePhoto(this);
});

$('.image').click(function(){
            $('.selected').removeClass('selected');
            $(this).addClass('selected');
        });
.image {
  height: 100px;
  width: 100px;
  cursor:pointer;
}
.selected {
  border: 1px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
  <input type="file" value="Add new image" id="addPhoto">
</form>
<ul class="list">
  <li><img src="https://blog.shareaholic.com/wp-content/uploads/2015/06/shortlink.png" alt="" class="image"></li>
  <li><img src="http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a" alt="" class="image"></li>
</ul>

And Demo

  • You need to use a delegated event handler on elements which are appended to the DOM after the page loads. See the question I marked as duplicate for more information – Rory McCrossan Aug 21 '16 at 12:42
  • Yeah but i can't fully understand it. Maybe I need a specified example in my case. Soo ... –  Aug 21 '16 at 12:53
  • Change this: `$('.image').click(function(){` to this: `$('.list').on('click', '.image', function() {` – Rory McCrossan Aug 21 '16 at 12:53

0 Answers0