Reputation: 8982
I just noticed something unusual. This is what I want to accomplish:
I want a div to be shown when I click a link
I want the div to disappear when I click somewhere else in the document
I don't want it to disappear when I click the div itself
Something like this:
JS:
(function() {
var box = $('#box');
$(document).on('click', function() {
if (box.css('display') == 'block') {
box.css('display', 'none');
}
});
$('#start').on('click', function(e) {
box.css({
'text': 'Box',
'position': 'absolute',
'top': '50px',
'left': '0',
'background': '#EEE',
'border': '1px solid #555',
'width': '200px',
'height': '50px',
'display': 'block'
});
e.stopPropagation();
});
box.on('click', function(e) {
e.stopPropagation();
});
})();
That fiddle works just fine but when I tested that in Firefox (15.0.1), if you right-click on the div, it dissapears, which is not the behavior I'm looking for. It seems that stopPropagation() works for clicks but not right-clicks in Firefox. Chrome keeps right-clicks from propagating to the document.
How can I fix it?
Thanks
Upvotes: 2
Views: 551
Reputation: 3498
Use the event.which method to detect which button was clicked. Here's an example in jsfiddle.
$(document).on('click', function(event) {
if (event.which == 1 && box.css('display') == 'block') {
box.css('display', 'none');
}
});
Upvotes: 5
Reputation: 575
Edited to actually work...
Sorry about that, the events didn't work as anticipated. You could handle it with mouse-overs.
(function() {
var box = $('#box');
var clicky = true;
$(document).on('click', function() {
if (box.css('display') == 'block' && clicky) {
box.css('display', 'none');
}
});
$('#start').on('click', function(e) {
box.css({
'text': 'Box',
'position': 'absolute',
'top': '50px',
'left': '0',
'background': '#EEE',
'border': '1px solid #555',
'width': '200px',
'height': '50px',
'display': 'block'
});
e.stopPropagation();
});
box.mouseenter(function(e) {
clicky = false;
});
box.mouseout(function(e) {
clicky = true;
});
})();
Upvotes: 0