Nyagolova Nyagolova - 3 months ago 11x
Javascript Question

Toggle hide/show div works on button, but not on link?

I want to be able to show and hide a certain div when clicking on a link, but my code works only if I use a button. Why is this happening and how can i fix it?

Here is my code:

.popup {
position: relative;
display: inline-block;

.popup-content {
display: none;
position: absolute;
width: 1000px;


.show {

<div class="popup">

<button onclick="showPopup()" class="btnPopup">POPUP FROM BUTTON</button>

<a class="linkStyle" onclick="javascript:showPopup()" href="#" return false;>POPUP FROM LINK</a>

<div id="myPopup" class="popup-content" style="border:1px; border-style:solid; margin:10px; padding: 10px;width:200px;">

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatibus quasi voluptas impedit. Culpa impedit?


/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function showPopup() {
return false;

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.btnPopup')) {

var dropdowns = document.getElementsByClassName("popup-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {

Also here it is a link for codepen:


The popup opens alright, but your function for closing the popup is causing the problems.

You attach a listener to the whole window's "onclick" function, and then proceed to close the popup - unless the event target matched ".btnPopup", i.e. your button was clicked.

So what's happening is:

  1. You click on the button, its "onclick" function shows the popup, the window's "onclick" function runs, but doesn't do anything because the event target matches '.btnPopup'
  2. You click on the link, its "onclick" function shows the popup, the window's "onclick" function runs, and as the event taget does not match .btnPopup it closes the popup immediately.

You can fix it easily, by e.g. adding another class to both the button and the link and using that class in your window.onclick listener to check if "something" was clicked to open the popup:

<button onclick="showPopup()" class="btnPopup Popup">POPUP FROM BUTTON</button>
<a class="linkStyle Popup" onclick="showPopup()" href="#">POPUP FROM LINK</a>
window.onclick = function(event) {
    if (!event.target.matches('.Popup')) {
        //Proceed with closing the popup