Hide popover on same document link navigation

I have the following popover menu, clicking on a link will not hide the popover:
<nav id="mobile-nav" popover>
<a popovertarget="mobile-nav" popovertargetaction="hide" href="/">Home</a>
<a popovertarget="mobile-nav" href="/#products">Products</a>
<a popovertarget="mobile-nav" href="/#about">About&nbsp;Us</a>
<a popovertarget="mobile-nav" href="/#faq">FAQ</a>
</nav>
<button class="hamburger" popovertarget="mobile-nav">
<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 448 512">
<path
fill="white"
d="M0 96C0 78.3 14.3 64 32 64l384 0c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 128C14.3 128 0 113.7 0 96zM0 256c0-17.7 14.3-32 32-32l384 0c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 288c-17.7 0-32-14.3-32-32zM448 416c0 17.7-14.3 32-32 32L32 448c-17.7 0-32-14.3-32-32s14.3-32 32-32l384 0c17.7 0 32 14.3 32 32z"
/>
</svg>
</button>
<nav id="mobile-nav" popover>
<a popovertarget="mobile-nav" popovertargetaction="hide" href="/">Home</a>
<a popovertarget="mobile-nav" href="/#products">Products</a>
<a popovertarget="mobile-nav" href="/#about">About&nbsp;Us</a>
<a popovertarget="mobile-nav" href="/#faq">FAQ</a>
</nav>
<button class="hamburger" popovertarget="mobile-nav">
<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 448 512">
<path
fill="white"
d="M0 96C0 78.3 14.3 64 32 64l384 0c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 128C14.3 128 0 113.7 0 96zM0 256c0-17.7 14.3-32 32-32l384 0c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 288c-17.7 0-32-14.3-32-32zM448 416c0 17.7-14.3 32-32 32L32 448c-17.7 0-32-14.3-32-32s14.3-32 32-32l384 0c17.7 0 32 14.3 32 32z"
/>
</svg>
</button>
4 Replies
Zach
ZachOP2mo ago
So popover target only works on buttons but I would like one click to both follow the link and hide the popover
John Patrick Onyango
try adding onclick events to close the popover i.e
document.getElementById('mobile-nav').addEventListener('click', (e) => {
if (e.target.tagName === 'A') {
e.target.closest('[popover]').hidePopover();
}
});
document.getElementById('mobile-nav').addEventListener('click', (e) => {
if (e.target.tagName === 'A') {
e.target.closest('[popover]').hidePopover();
}
});
Zach
ZachOP2mo ago
oh I forgot to mention, I'm trying to do this with just CSS. It shouldn't need JS that JS checks out though fairly straightforward with JS, maybe I should submit an issue to w3c
John Patrick Onyango
with css its going to be a lil tricky,,, not sure if will work though
<style>
:target ~ [popover] {
display: none;
}
</style>
<style>
:target ~ [popover] {
display: none;
}
</style>

Did you find this page helpful?