Dan Dan - 1 year ago 84
CSS Question

target rest of the document, stop scrolling and toggleClass

I'm working on a dropdown menu, and I'm using jQuery to manipulate the DOM. So far, I'm able to toggle the menu into and out of view. Whenever the menu is in view, I have it CSS position property set to fixed with the top, left and bottom properties set to Zero and its width to 90% as follows


My problem is two-fold

  1. When I scroll on the menu (for instance, when testing), the rest of
    the document scrolls as well. I would like to confine scrolling to
    the menu container whenever the menu is in view.

    //rest of body doesn't scroll

  2. Second, since the menu width is set to 90%, I would like to toggle
    the menu out of view whenever one clicks outside the menu container.

    $('rest of body').on('click', function(){
    //Toggle menu out of view

Though I'm looking for a jQuery fix, any other implementation including direct manipulation with raw JavaScript will be appreciated.


Answer Source

The document will always scroll during a scroll action unless the mouse is over an element that itself has scroll, i.e. it has overflow: scroll or overflow: auto and a fixed height

With this in mind, modify your menu to have

overflow: scroll;
height: 300px; /* for example */

Next, how to close it on blur. The logic here is you want to invoke closure on any click that is not within the menu - in other words, the click should not be on the menu itself or any of its child/descendent elements. Here's how:

$('body').on('click', '*', function() {
    if (!$(this).closest('.menu-container').length) $('.menu-container').hide();

Since closest() checks the matched elements and its parent/ancestors against the passed selectors, it's a good choice for this sort of check.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download