'Popper.js: How to close popup when clicking outside
I'm using Popper.js to show a popup elment having the class .js-share-cf-popover when clicking elements with class .js-share-cf-btn.
But I want the popup to close only when I click outside of it. Here my actual code that show the popup:
var reference = $('.js-share-cf-btn');
var popover = $('.js-share-cf-popover');
popover.hide();
$(document).on('click', reference, function(e) {
e.preventDefault();
popover.show();
var popper = new Popper(reference, popover, {
placement: 'top',
});
});
I found something here but I can't get it works
Here My jsfiddle
Solution 1:[1]
Something like this should do the trick (by checking the target when you are clicking somewhere):
$(function() {
var ref = $('.js-share-cf-btn');
var popover = $('.js-share-cf-popover');
popover.hide();
$(document).on('click', function(e) {
var target = $(e.target);
if (target.is(ref) || target.is(popover) ) {
e.preventDefault();
popover.show();
var popper = new Popper(ref, popover, {
placement: 'right',
});
}else {
popover.hide();
}
});
});
Solution 2:[2]
For those using React, I created a gist of an HOC that you can attach to any component to close it when clicked outside:
https://gist.github.com/elie222/850bc4adede99650508aba2090cd5da1
Solution 3:[3]
I found a really simple solution to this.
jQuery version
<div class="Popper">
<div class="stopPropagation">
<p>Clicking on me won't close the Popper</p>
</div>
</div>
$('.stopPropagation').on('click touchend', function(e) {
e.stopPropagation()
})
Since the click event does not propagate up to the Popper, the Popper will not closed when clicked.
React version
<Popper>
{/* eslint-disable-next-line jsx-a11y/click-events-have-key-events */}
<div onClick={e => e.stopPropagation()} role="none">
<p>Clicking on me won't close the Popper</p>
</div>
</Popper>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Quentin Roger |
| Solution 2 | Eliezer Steinbock |
| Solution 3 | Daniel Tonon |
