Reputation: 97
I'm injecting HTML from another div on the page into a div and then adding a class of .show, like so:
var $boxItem = $('.box-grid__item'),
$htmlData = $($boxItem).find('.box-grid__item-content').html();
$boxItem.click(function () {
$('.box-grid__item-content-popup').html($htmlData).addClass('show');
});
The HTML that gets injected is:
<div class="close-btn" aria-label="Close">
<span></span>
<span></span>
</div>
<h2 class="box-grid__item-content-heading">Name and Surname</h2>
<p class="box-grid__item-content-title">Title</p>
<p class="box-grid__item-content-text">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
This works as expected but now I would like to remove the .show. I've tried this but it doesn't fire:
$('.close-btn').click(function () {
$('.box-grid__item-content-popup').removeClass('show');
});
Any help will be much appreciated ;)
Upvotes: 1
Views: 71
Reputation: 23738
// create a reference to the old `.html()` function
var htmlOriginal = $.fn.html;
// redefine the `.html()` function to accept a callback
$.fn.html = function(html,callback){
// run the old `.html()` function with the first parameter
var ret = htmlOriginal.apply(this, arguments);
// run the callback (if it is defined)
if(typeof callback == "function"){
callback();
}
// make sure chaining is not broken
return ret;
}
// test it all works as expected (including chaining)
$("#mything").html("<div>My Thing</div>",function(){
console.log("Just did my thing");
}).css({color: 'red'})
See fiddle
Upvotes: 0
Reputation: 14541
Since you are dynamically inserting the HTML, your event handler should be something like:
$('.box-grid__item-content-popup').on("click", '.close-btn', function () {
$('.box-grid__item-content-popup').removeClass('show');
})
This means that the events bubbling to .box-grid__item-content-popup
will be captured, but the handler will fire when the event was triggered on .close-btn
or one of its descendents.
Ref: See delegated events section at http://api.jquery.com/on/
Upvotes: 3
Reputation: 2783
I assume you have your .click
code before you insert the html.
What you could do, is rewrite your function, so it triggers on the .box-grid__item
and then put a selector on that.
$(".box-grid__item").on("click", ".close-btn", function(){
$('.box-grid__item-content-popup').removeClass('show');
});
Upvotes: 0