Bind event to dynamically created elements with jQuery
I am loading multiple images and put them inside some divs that onclick should switch to some class. Should I place the part where I add the onclick event inside the ajax success function? Many thanks!
I'm using jquery "on" but doesn't seem to work. I probably missed something.
Here is my code:
JavaScript:
$(".box-picture-selected > div > div").on( 'click' , function () {
$(this).toggleClass('image-selected');
});
$('#uploadForm').submit(function (e) {
e.preventDefault();
var form = new FormData($('form')[0]);
var files = document.getElementsByClassName('pics');
for (var i=0; i<files.length; i++) {
form.append("files[" + i + "]", files[i][0]); // add receipt to form
}
form.append('action', 'upload-photos'); // specify action
form.append('csrfmiddlewaretoken', '{{ csrf_token() }}');
$.ajax({
url: '{{url("/photos/device")}}',
type: 'POST',
data: form,
cache: false,
processData: false,
contentType: false,
success:function(data) {
$.each($(data), function(key, value) {
var displayDiv = document.getElementById("displayPics");
var grid = document.createElement("div");
grid.setAttribute("class", 'col-md-3 col-sm-4 col-xs-6 grid-changes image-selected');
var picDiv = document.createElement("div");
picDiv.setAttribute("class" , 'col-xs-12 images-box');
picDiv.setAttribute("style", 'background-image: url({{ url('fit/?image='.urlencode(asset('filestorage/temp'))) }}' + '%2F' + value + ');' );
displayDiv.appendChild(grid);
grid.appendChild(picDiv);
});
},
error: function(xhr, desc, err) {
// I have some error handling logic here
}
});
});
HTML:
<div id="displayPics" class="col-xs-12 grid-4-picture">
@if (isset($files) && !empty($files))
@foreach ($files as $photo)
<div class="col-md-3 col-sm-4 col-xs-6 grid-changes">
<div class="col-xs-12 images-box" style="background-image: url({{ url('fit/?image='.urlencode(asset('filestorage/temp/'.$photo))) }});"></div>
<input type="hidden" value="{{ url('fit/?image='.urlencode(asset('filestorage/temp/'.$photo))) }}">
</div>
@endforeach
@endif
</div>
source to share
For a dynamically created element, you must use . live () is however live()
deprecated in 1.7 in favor on()
, and removed entirely in 1.9
. Signature live()
:
If you have a larger version jQuery
than 1.9
you can use jQuery.fn.on
I would recommend using .on
below, this is the .on function signature
$(document).on( eventName, selector, function(){} );
$("body").on("click", "#YOUR_DYNAMICALLY_CREATED_ELEMENT", function(event){
//Do Some stuff
});
Solved version:
$("body").on('click', '.box-picture-selected > div > div', function(event)
{
$(this).toggleClass('image-selected');
});
source to share