0

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.

user944513
  • 12,247
  • 49
  • 168
  • 318

3 Answers3

0

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;
  })
brk
  • 48,835
  • 10
  • 56
  • 78
0

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.

epascarello
  • 204,599
  • 20
  • 195
  • 236
0
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();
});
aisensiy
  • 1,460
  • 3
  • 26
  • 42