could you please tell me why click event is not firing when I am taking selector
in object
; here is my code https://jsbin.com/seregezahe/1/edit?html,js,output
(function(){
$(function(){
var config ={
btn:$('#btn'),
hello:$('.hello'),
bodyClickEvent: $("body"),
overlayClick: $('.overlay'),
closeBtnSelector: '#closeBtn',
};
config.btn.click(function(){
$('#container').append($('#overlay').html())
$('.popupdata').html('<div class="hello">xxxx</div><a href="javascript:void(0)" id="closeBtn" >X Close</a></div>');
})
config.bodyClickEvent.on("click", config.closeBtnSelector, function () {
//why it is not working
config.overlayClick.fadeOut(500);
config.overlayClick.remove();
// below code is working fine
//$('.overlay').fadeOut(500);
//$('.overlay').remove();
});
})
})()
why these two line are not working
config.overlayClick.fadeOut(500);
config.overlayClick.remove();
when I run my code it show a button
when I click on button some html is show
with close button text .When I click close button it is not fadeout
my html and remove.
Update the config object after updating the dom
config.btn.click(function(){
$('#container').append($('#overlay').html())
$('.popupdata').html('<div class="hello">xxxx</div>'+
'<a href="" id="closeBtn" >X Close</a></div>');
config.overlayClick= $('.overlay');
config.closeBtnSelector = '#closeBtn'
return false;
})
The problem is your are selecting the elements before they are added to the page. You need to populate the selectors after you add them to the page.
....append(...);
....html(...);
config.overlayClick = $('.overlay');
...
or you need to select the items instead of using the variable.
var config ={
btn:$('#btn'),
hello:$('.hello'),
bodyClickEvent: $("body"),
overlayClick: $('#overlay'),
closeBtnSelector: '#closeBtn',
};
Because the element #overlay
is not exist when you call $('#overlay')
above, so the $('#overlay')
return an empty list.
The following code should work:
var config ={
btn:$('#btn'),
hello:$('.hello'),
bodyClickEvent: $("body"),
overlayClickSelector: '#overlay',
closeBtnSelector: '#closeBtn',
};
config.bodyClickEvent.on("click", config.closeBtnSelector, function () {
$(config.overlayClick).remove();
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.