(document).mousedown - a little JS snippet

By jason

Bit of a short post from me this week (a longer one coming next week, I promise). Just wanted to cover a little bit of jQuery I discovered that helped me a lot with a particular problem I couldn't seem to beat.

I had a contentEditable area that showed a little admin toolbar above it when you focused on the element, and I needed to remove it as soon as the user clicked away from the area. Unfortunately, the "blur()" implementation for contentEditable areas is a little bit all over the place and a user can get around it occasionally. It doesn't seem to fire, for example, when you immediately highlight some other text rather than just clicking away.

So, I came up with this snippet:

$(document).mousedown(function (e) {

if (!$(e.target).is('.editable, .editable *')) {

$('.top-bar').remove();

$('div.active').removeClass('active');

}

});

This basically fires a mousedown event whenever you click anywhere on the document. It checks whether the target is within the editable area and if it's not, it removes the admin toolbar and associated CSS class.

Related posts