I made a modal plugin but for some reason one of the divs that I generate isn’t getting a click event listener that I am attaching to it.
<a class="close" id="js-close-modal"></a> is what I’m referring to. I’m using jQuery’s on, but that doesn’t seem to help.
var $caller = $(this);
var $modal = $('.modal');
$caller.on('click', $caller, function(e) {
e.stopPropagation();
$('#js-close-modal').on('click', $('#js-close-modal'), function(e) {
$('.modal_outer').remove();
$('#modal_page_cover').remove();
});
var modal_outer = $('<div />');
modal_outer.addClass('modal_outer');
modal_outer.css({
top: ($(window).scrollTop()) + 'px'
});
var $div = $('<div />');
var modal = $('<div />');
modal.addClass('modal');
var modal_inner = $('<div />');
modal_inner.addClass('modal_inner');
modal.append(modal_inner);
modal_outer.append(modal);
var body = $('body');
body.append(modal_outer).hide().fadeIn(100);
modal_inner.text('yo');
var close = $('<a />');
close.addClass('close').attr('id', 'js-close-modal');
close.insertBefore(modal_inner);
var page_cover = $('<div />');
page_cover.attr('id', 'modal_page_cover');
body.prepend(page_cover);
});
Demo: JSFiddle
Any idea why?
You’re passing a jQuery object in as your selector on the
$.onmethod. You should instead be passing in a selector alone:You made the same error on
$caller.on(). You don’t bind$.on()to the element you’re clicking, you bind it to one of the parents of that element. I’ve bound the even to thebodyelement, but you should ideally bind it to a much closer parent.Making the change I demonstrated above fixes your close button: http://jsfiddle.net/P5B4q/22/
Of course you’re creating the close button in the same code, so event delegation isn’t really necessary. You could do away with the code above, and modify your close button upon creation:
Replace that with: