# Using jQuery 1.7 .on() and event.stopPropagation to close boxes when clicking in document body

I have the following code which works but seems like it could be improved. I'm not sure if I'm using event.stopPropagation() correctly or if it is the best solution.

The elements are loaded via AJAX and so need to have .on() (previously .live(), which is now deprecated in jQuery 1.7).

I've used the example given here as a basis.

$('html').on('click', '.poster:not(.active) .image-effect', function (event) { var obj =$(this).parent();

// If there are no .close spans
if (obj.find('.close').length === 0) {

// Add the close element by javascript to remain semantic
obj.find('.quick-view').append('<span class="close">&times;</span>');
}

// Close any open Quick Views
closeQuickView();

// Add the active class (controls opacity)

// Fade in the Quick View

event.preventDefault();
event.stopPropagation();

});

$('html').on('click', '.active', function () { return false; });$('html').on('click', '.close', function () {
closeQuickView();
});

$('html').on('click', '.quick-view', function (event) { event.stopPropagation(); }); // Close the QuickView with a button$('html').on('click', function () {
closeQuickView();
});

function closeQuickView() {
$('.poster').removeClass('active');$('.quick-view').fadeOut(200, 'easeInOutQuint');
}


For some reason clicking the document isn't working in Chrome (the closeQuickView is not being called) which may be an indicator that the code is not functioning 100%.

My markup is as follows:

<figure class="grid_2 box poster">
<a class="image-effect" href="#">
<img class="colour" src="path/to/image" />
<img class="bw" src="path/to/image" />
</a>
<div class="quick-view">

Content

</div>
</figure>


Is this the right way to approach the scenario? Are there any conflicting functions?

• Actually, you are not using on instead of live, but instead of delegate. Nov 5 '11 at 19:17
• Oh, really? Ok. I got a little confused as the .on() function in 1.7 seems to do the job of a few things. Nov 6 '11 at 14:34

$('html').on('click', '.poster', function(e) { var target =$(e.target);
var poster = $(this); if (!poster.hasClass('active')) { closeQuickView(); poster.addClass('active').find('.quick-view').fadeIn(200); } if (target.hasClass('quick-view') || target.hasClass('image-effect')) e.stopPropagation(); // prevent bubbling and thus closeClickView call below });$('html').on('click', closeQuickView);