jQuery .append()
This is perhaps an, inelegant way of doing this but... I am making my own lightbox window script with jQuery--for learning purposes more then anything else.
Using this script:
$(document).ready(function() {
$(".popout").hide();
$(".modal-links a").each(function(i){
$(this).click(function(){
$("body").append('<div class="overlay"></div>')
$(".popout").append('<a class="close" href="#">Close</a>')
var modal = $(".popout").eq(i),
modalWidth = modal.width(),
modalHeight = modal.height();
modal.css({
"width":modalWidth,
"height":modalHeight,
"margin-left":-(modalWidth/2)})
.show().siblings(".popout").hide();
});
});
$(".close").click(function(){
$(".popout").hide();
$(".overlay").hide();
});
});
I am able to append anchor link with a class of .close. This works, when I view source, it is put in the markup as I would like it. However, in the following function I try to target this appended class and use a click event to trigger the hiding of the modal windo开发者_StackOverfloww and it's overlay in the background. This does not work. Yet, if I just copy the a class="close"
markup into my actual markup (without JS) it does close when clicked. Any ideas?
you need to either add your click handler when you create the close link, or delegate the click handler as a live
click function.
What's happening is that your $('.close').click(...
selector isn't selecting any elements as the close link doesn't exist yet.
EDIT to add:
A fix would be to change it to $('.close').live('click', function...
The elements are appended asynchronously.
Looks like you need to use the .live()
method. Since your anchor with the close
class is only created after the click
occurs on a modal-links
anchor, jQuery can't wire it up at the document.ready
event.
Edit, correction:
The .live
method gets around this by attaching an event to the root of the DOM tree that checks whether the target element matches the selectors given, and then executes the appropriate function.
$('.close').live('click', function() {
$(".popout").hide();
$(".overlay").hide();
});
精彩评论