Javascript closing a dropdown with document.onclick

236
June 01, 2018, at 7:20 PM

I have a dropdown dropdown using ul and li:

<img class="options_toggle" src="assets/down_arrow.png"onclick="toggle_display('options');"/>
<ul id="options" class="options_content hide">
      <li>
           option one
      </li>
</ul>

the options_toggle function swaps back and forth between the "hide" and "show" class in the options ul. Now I want to only hide it when the user clicks anywhere except the options toggle:

$(document).ready(function () {
document.onclick = function(e) {
    // prevent the dropdown from closing instantly when you click the toggle to open it
    $(".options_toggle").click(function (e) {
        e.stopPropagation();
    });
    // hide the dropdown
    $(".options_content").removeClass("show");
    $(".options_content").addClass("hide");
};
});

But the problem is that the first time they load the page they have to click somewhere once before clicking the toggle. After the first click it works fine, they just have to click twice at first which can be annoying.

Any ideas what it's doing and why it cancels or ignores the first toggle? Thanks.

Answer 1

It's usually wrong to add an event handler inside another event handler. Just bind your $(".options_toggle").click() handler at top-level.

$(document).ready(function() { 
  $(".options_toggle").click(function(e) { 
    // prevent the dropdown from closing instantly when you click the toggle to open it 
    e.stopPropagation(); 
  }); 
 
  $(document).click(function(e) { 
    // hide the dropdown 
    $(".options_content").removeClass("show"); 
    $(".options_content").addClass("hide"); 
  }); 
});

Rent Charter Buses Company
READ ALSO
Disable click on div but not hover?

Disable click on div but not hover?

I'm trying to disable click on div, but not hoverI'm trying with css: pointer-events:none;, but it also disables hover effects

230
Trouble grasping the usage of react or CSS [on hold]

Trouble grasping the usage of react or CSS [on hold]

For example, you can create a scrolling function in CSS using

144
Remove scroll function upon window resize/media query

Remove scroll function upon window resize/media query

I have a navigation menu set to display:none, which appears upon scroll and disappears once back at the top

164
CSS Content with a Font Awesome light icon

CSS Content with a Font Awesome light icon

I have the following CSS code

292