Marco Marco - 1 month ago 5
Javascript Question

jQuery $(document).on( eventName, selector, function(){} ) not working

I had a click function which functioned when I had this elements hidden on page load, and then showed them later. Now I am appending those elements on click after the page has loaded, and the function of course doesn't work. I thought I would fixed the problem with

load()
function but it still doesn't work. This is the html I append on click:

$('#magazine-detail')[0].innerHTML = '<section id="magazine-detail" class="magazine-detail"><div class="large-6 medium-6 small-12 columns"><div class="magazine-hero"><img id="image" src="/imagecache/cover/' + magazineImage + '" alt="' + name + '" /><div class="magazine-preview-nav"><div class="right-arrow" id="forward"><img src="/img/right-arrow-black.svg" /><p>Neste utgivelse</p></div><div class="left-arrow" id="back"><img src="/img/left-arrow-black.svg" /><p>Forrige utgivelse</p></div></div></div></div><div class="large-6 medium-6 small-12 columns"><div class="row"><div class="small-6 columns magazine-title"><h1 id="name"></h1></div></div><p id="summary"></p><img id="issueImage" src="" alt="" /><p></p><button class="button primary expand">Kjøp abonnement - 1 måned gratis</button><button class="button secondary expand">Bla igjennom arkivet</button></div></section>';


There I create
#forward
and
#back
elements, for which I have functions on click in my script:

$(document).ready(function () {
var imagesIndex = 0;
nextImage = 0;
loadedImages = new Array();

function preload() {
for (i = 0; i < 2; i++) {
if (nextImage < images.length) {
var img = new Image();
img.src = '/imagecache/cover/' + images[nextImage];
loadedImages[nextImage] = img;
++nextImage;
}
}
}

$('#forward').load('click', function() {
imagesIndex++;
preload();

if (imagesIndex > (loadedImages.length - 1)) {
imagesIndex = loadedImages.length - 1;
}

$('#image').attr({"src" : loadedImages[imagesIndex].src, "alt" : name});
});

$('#back').load('click', function() {
imagesIndex--;

if (imagesIndex < 0) {
imagesIndex = 0;
}

$('#image').attr({"src" : loadedImages[imagesIndex].src, "alt" : name});
});
});


I have tried with:

$(document).on('click','#forward', function() {
console.log('entered');
imagesIndex++;
preload();

if (imagesIndex > (loadedImages.length - 1)) {
imagesIndex = loadedImages.length - 1;
}

$('#image').attr({"src" : loadedImages[imagesIndex].src, "alt" : name});
});

$(document).on('click','#forward', function() {
imagesIndex--;

if (imagesIndex < 0) {
imagesIndex = 0;
}

$('#image').attr({"src" : loadedImages[imagesIndex].src, "alt" : name});
});


But nothing gets logged when I click on the element.

Answer
$("#existingParent").on("click", ".child", function() {
  // do stuff
});