Home > Software design >  How to allow Body to scroll when overlay is open
How to allow Body to scroll when overlay is open

Time:10-06

I want to be able to scroll through the body element, even when I have the overlay opened.

Currently the content in the overlay scrolls, but when the overlay is open, and I try to scroll for the content beneath the overlay, nothing happens.

How can I also make the background content scrollable?

var body = document.body,
  overlay = document.querySelector('.overlay'),
  overlayBtts = document.querySelectorAll('button[class$="overlay"]'),
  openingBtt;
[].forEach.call(overlayBtts, function(btt) {

  btt.addEventListener('click', function() {

    /* Detect the button class name */
    var overlayOpen = this.className === 'open-overlay';

    /* storing a reference to the opening button */
    if (overlayOpen) {
      openingBtt = this;
    }

    /* Toggle the aria-hidden state on the overlay and the 
       no-scroll class on the body */
    overlay.setAttribute('aria-hidden', !overlayOpen);
    body.classList.toggle('noscroll', overlayOpen);

    /* On some mobile browser when the overlay was previously
       opened and scrolled, if you open it again it doesn't 
       reset its scrollTop property after the fadeout */
    setTimeout(function() {
      overlay.scrollTop = 0;
    }, 1000);

    /* forcing focus for Assistive technologies but note:
    - if your modal has just a phrase and a button move the
      focus on the button
    - if your modal has a long text inside (e.g. a privacy
      statement) move the focus on the first heading inside 
      the modal
    - otherwise just focus the modal.

    When you close the overlay restore the focus on the 
    button that opened the modal.
    */
    if (overlayOpen) {
      overlay.focus();
    } else {
      openingBtt.focus();
      openingBtt = null;
    }

  }, false);

});

var body = document.body,
  overlay = document.querySelector('.overlay'),
  overlayBtts = document.querySelectorAll('button[class$="overlay"]');

[].forEach.call(overlayBtts, function(btt) {

  btt.addEventListener('click', function() {

    /* Detect the button class name */
    var overlayOpen = this.className === 'open-overlay';

    /* Toggle the aria-hidden state on the overlay and the 
       no-scroll class on the body */
    overlay.setAttribute('aria-hidden', !overlayOpen);
    body.classList.toggle('noscroll', overlayOpen);

    /* On some mobile browser when the overlay was previously
       opened and scrolled, if you open it again it doesn't 
       reset its scrollTop property after the fadeout */
    setTimeout(function() {
      overlay.scrollTop = 0;
    }, 1000)
  }, false);
});
/* to the body element */

.noscroll {
  overflow: hidden;
}

@media (min-device-width: 1025px) {
  .noscroll {
    padding-right: 15px;
  }
}

.overlay {
  position: fixed;
  overflow-y: scroll;
  inset: 0;
}

[aria-hidden="true"] {
  transition: opacity 1s, z-index 0s 1s;
  width: 100vw;
  z-index: -1;
  opacity: 0;
}

[aria-hidden="false"] {
  transition: opacity 1s;
  width: 100%;
  z-index: 1;
  opacity: 1;
}

:focus {
  outline: 2px yellowgreen solid;
}


/* this code is not strictly necessary: just to make this demo a bit pleasant */

.overlay div {
  margin: 15vh auto;
  width: 80%;
  max-width: 650px;
  padding: 30px;
  min-height: 200vh;
  background: rgba(255, 255, 255, .95);
}

.overlay {
  background: rgba(40, 40, 40, .75);
}

* {
  box-sizing: border-box;
}

button {
  padding: 1.5em 4em;
  cursor: pointer;
}

pre {
  background: #fafafa;
  padding: 15px;
  border: 1px #ccd dashed;
}

pre p {
  margin: 5vh 0;
}
<p>In a few minutes there was, so far as the soldier could see, not a living thing left upon the common, and every bush and tree upon it that was not already a blackened skeleton was burning. The hussars had been on the road beyond the curvature of the ground,
  and he saw nothing of them. He heard the Martians rattle for a time and then become still. The giant saved Woking station and its cluster of houses until the last; then in a moment the Heat-Ray was brought to bear, and the town became a heap of fiery
  ruins. Then the Thing shut off the Heat-Ray, and turning its back upon the artilleryman, began to waddle away towards the smouldering pine woods that sheltered the second cylinder. As it did so a second glittering Titan built itself up out of the pit.</p>

<p>The second monster followed the first, and at that the artilleryman began to crawl very cautiously across the hot heather ash towards Horsell. He managed to get alive into the ditch by the side of the road, and so escaped to Woking. There his story became
  ejaculatory. The place was impassable. It seems there were a few people alive there, frantic for the most part and many burned and scalded. He was turned aside by the fire, and hid among some almost scorching heaps of broken wall as one of the Martian
  giants returned. He saw this one pursue a man, catch him up in one of its steely tentacles, and knock his head against the trunk of a pine tree. At last, after nightfall, the artilleryman made a rush for it and got over the railway embankment.</p>

<button type="button" >OPEN LAYER</button>

<p>Since then he had been skulking along towards Maybury, in the hope of getting out of danger Londonward. People were hiding in trenches and cellars, and many of the survivors had made off towards Woking village and Send. He had been consumed with thirst
  until he found one of the water mains near the railway arch smashed, and the water bubbling out like a spring upon the road.</p>

<p>That was the story I got from him, bit by bit. He grew calmer telling me and trying to make me see the things he had seen. He had eaten no food since midday, he told me early in his narrative, and I found some mutton and bread in the pantry and brought
  it into the room. We lit no lamp for fear of attracting the Martians, and ever and again our hands would touch upon bread or meat. As he talked, things about us came darkly out of the darkness, and the trampled bushes and broken rose trees outside the
  window grew distinct. It would seem that a number of men or animals had rushed across the lawn. I began to see his face, blackened and haggard, as no doubt mine was also.</p>

<p>When we had finished eating we went softly upstairs to my study, and I looked again out of the open window. In one night the valley had become a valley of ashes. The fires had dwindled now. Where flames had been there were now streamers of smoke; but
  the countless ruins of shattered and gutted houses and blasted and blackened trees that the night had hidden stood out now gaunt and terrible in the pitiless light of dawn. Yet here and there some object had had the luck to escape--a white railway signal
  here, the end of a greenhouse there, white and fresh amid the wreckage. Never before in the history of warfare had destruction been so indiscriminate and so universal. And shining with the growing light of the east, three of the metallic giants stood
  about the pit, their cowls rotating as though they were surveying the desolation they had made.</p>

<p>It seemed to me that the pit had been enlarged, and ever and again puffs of vivid green vapour streamed up and out of it towards the brightening dawn--streamed up, whirled, broke, and vanished.</p>

<p>Beyond were the pillars of fire about Chobham. They became pillars of bloodshot smoke at the first touch of day.</p>

<p>As the dawn grew brighter we withdrew from the window from which we had watched the Martians, and went very quietly downstairs.</p>

<p>The artilleryman agreed with me that the house was no place to stay in. He proposed, he said, to make his way Londonward, and thence rejoin his battery--No. 12, of the Horse Artillery. My plan was to return at once to Leatherhead; and so greatly had the
  strength of the Martians impressed me that I had determined to take my wife to Newhaven, and go with her out of the country forthwith. For I already perceived clearly that the country about London must inevitably be the scene of a disastrous struggle
  before such creatures as these could be destroyed.</p>

<p>The train passed rapidly across the State of Iowa, by Council Bluffs, Des Moines, and Iowa City. During the night it crossed the Mississippi at Davenport, and by Rock Island entered Illinois. The next day, which was the 10th, at four o'clock in the evening,
  it reached Chicago, already risen from its ruins, and more proudly seated than ever on the borders of its beautiful Lake Michigan.</p>

<p>Nine hundred miles separated Chicago from New York; but trains are not wanting at Chicago. Mr. Fogg passed at once from one to the other, and the locomotive of the Pittsburgh, Fort Wayne, and Chicago Railway left at full speed, as if it fully comprehended
  that that gentleman had no time to lose. It traversed Indiana, Ohio, Pennsylvania, and New Jersey like a flash, rushing through towns with antique names, some of which had streets and car-tracks, but as yet no houses. At last the Hudson came into view;
  and, at a quarter-past eleven in the evening of the 11th, the train stopped in the station on the right bank of the river, before the very pier of the Cunard line.</p>

<p>The China, for Liverpool, had started three-quarters of an hour before!</p>

<p>The China, in leaving, seemed to have carried off Phileas Fogg's last hope. None of the other steamers were able to serve his projects. The Pereire, of the French Transatlantic Company, whose admirable steamers are equal to any in speed and comfort, did
  not leave until the 14th; the Hamburg boats did not go directly to Liverpool or London, but to Havre; and the additional trip from Havre to Southampton would render Phileas Fogg's last efforts of no avail. The Inman steamer did not depart till the next
  day, and could not cross the Atlantic in time to save the wager.</p>

<p>Mr. Fogg learned all this in consulting his Bradshaw, which gave him the daily movements of the trans-Atlantic steamers.</p>

<p>Passepartout was crushed; it overwhelmed him to lose the boat by three-quarters of an hour. It was his fault, for, instead of helping his master, he had not ceased putting obstacles in his path! And when he recalled all the incidents of the tour, when
  he counted up the sums expended in pure loss and on his own account, when he thought that the immense stake, added to the heavy charges of this useless journey, would completely ruin Mr. Fogg, he overwhelmed himself with bitter self-accusations. Mr.
  Fogg, however, did not reproach him; and, on leaving the Cunard pier, only said: "We will consult about what is best to-morrow. Come."</p>

<button type="button" >OPEN LAYER</button>

<p>The party crossed the Hudson in the Jersey City ferryboat, and drove in a carriage to the St. Nicholas Hotel, on Broadway. Rooms were engaged, and the night passed, briefly to Phileas Fogg, who slept profoundly, but very long to Aouda and the others,
  whose agitation did not permit them to rest.</p>

<p>The next day was the 12th of December. From seven in the morning of the 12th to a quarter before nine in the evening of the 21st there were nine days, thirteen hours, and forty-five minutes. If Phileas Fogg had left in the China, one of the fastest steamers
  on the Atlantic, he would have reached Liverpool, and then London, within the period agreed upon.</p>

<p>Mr. Fogg left the hotel alone, after giving Passepartout instructions to await his return, and inform Aouda to be ready at an instant's notice. He proceeded to the banks of the Hudson, and looked about among the vessels moored or anchored in the river,
  for any that were about to depart. Several had departure signals, and were preparing to put to sea at morning tide; for in this immense and admirable port there is not one day in a hundred that vessels do not set out for every quarter of the globe.
  But they were mostly sailing vessels, of which, of course, Phileas Fogg could make no use.</p>

<p>In a few minutes there was, so far as the soldier could see, not a living thing left upon the common, and every bush and tree upon it that was not already a blackened skeleton was burning. The hussars had been on the road beyond the curvature of the ground,
  and he saw nothing of them. He heard the Martians rattle for a time and then become still. The giant saved Woking station and its cluster of houses until the last; then in a moment the Heat-Ray was brought to bear, and the town became a heap of fiery
  ruins. Then the Thing shut off the Heat-Ray, and turning its back upon the artilleryman, began to waddle away towards the smouldering pine woods that sheltered the second cylinder. As it did so a second glittering Titan built itself up out of the pit.</p>

<p>The second monster followed the first, and at that the artilleryman began to crawl very cautiously across the hot heather ash towards Horsell. He managed to get alive into the ditch by the side of the road, and so escaped to Woking. There his story became
  ejaculatory. The place was impassable. It seems there were a few people alive there, frantic for the most part and many burned and scalded. He was turned aside by the fire, and hid among some almost scorching heaps of broken wall as one of the Martian
  giants returned. He saw this one pursue a man, catch him up in one of its steely tentacles, and knock his head against the trunk of a pine tree. At last, after nightfall, the artilleryman made a rush for it and got over the railway embankment.</p>

<button type="button" >OPEN LAYER</button>

<p>Since then he had been skulking along towards Maybury, in the hope of getting out of danger Londonward. People were hiding in trenches and cellars, and many of the survivors had made off towards Woking village and Send. He had been consumed with thirst
  until he found one of the water mains near the railway arch smashed, and the water bubbling out like a spring upon the road.</p>

<p>That was the story I got from him, bit by bit. He grew calmer telling me and trying to make me see the things he had seen. He had eaten no food since midday, he told me early in his narrative, and I found some mutton and bread in the pantry and brought
  it into the room. We lit no lamp for fear of attracting the Martians, and ever and again our hands would touch upon bread or meat. As he talked, things about us came darkly out of the darkness, and the trampled bushes and broken rose trees outside the
  window grew distinct. It would seem that a number of men or animals had rushed across the lawn. I began to see his face, blackened and haggard, as no doubt mine was also.</p>

<p>When we had finished eating we went softly upstairs to my study, and I looked again out of the open window. In one night the valley had become a valley of ashes. The fires had dwindled now. Where flames had been there were now streamers of smoke; but
  the countless ruins of shattered and gutted houses and blasted and blackened trees that the night had hidden stood out now gaunt and terrible in the pitiless light of dawn. Yet here and there some object had had the luck to escape--a white railway signal
  here, the end of a greenhouse there, white and fresh amid the wreckage. Never before in the history of warfare had destruction been so indiscriminate and so universal. And shining with the growing light of the east, three of the metallic giants stood
  about the pit, their cowls rotating as though they were surveying the desolation they had made.</p>

<p>It seemed to me that the pit had been enlarged, and ever and again puffs of vivid green vapour streamed up and out of it towards the brightening dawn--streamed up, whirled, broke, and vanished.</p>

<p>Beyond were the pillars of fire about Chobham. They became pillars of bloodshot smoke at the first touch of day.</p>

<p>As the dawn grew brighter we withdrew from the window from which we had watched the Martians, and went very quietly downstairs.</p>

<p>The artilleryman agreed with me that the house was no place to stay in. He proposed, he said, to make his way Londonward, and thence rejoin his battery--No. 12, of the Horse Artillery. My plan was to return at once to Leatherhead; and so greatly had the
  strength of the Martians impressed me that I had determined to take my wife to Newhaven, and go with her out of the country forthwith. For I already perceived clearly that the country about London must inevitably be the scene of a disastrous struggle
  before such creatures as these could be destroyed.</p>

<p>The train passed rapidly across the State of Iowa, by Council Bluffs, Des Moines, and Iowa City. During the night it crossed the Mississippi at Davenport, and by Rock Island entered Illinois. The next day, which was the 10th, at four o'clock in the evening,
  it reached Chicago, already risen from its ruins, and more proudly seated than ever on the borders of its beautiful Lake Michigan.</p>

<p>Nine hundred miles separated Chicago from New York; but trains are not wanting at Chicago. Mr. Fogg passed at once from one to the other, and the locomotive of the Pittsburgh, Fort Wayne, and Chicago Railway left at full speed, as if it fully comprehended
  that that gentleman had no time to lose. It traversed Indiana, Ohio, Pennsylvania, and New Jersey like a flash, rushing through towns with antique names, some of which had streets and car-tracks, but as yet no houses. At last the Hudson came into view;
  and, at a quarter-past eleven in the evening of the 11th, the train stopped in the station on the right bank of the river, before the very pier of the Cunard line.</p>

<p>The China, for Liverpool, had started three-quarters of an hour before!</p>

<p>The China, in leaving, seemed to have carried off Phileas Fogg's last hope. None of the other steamers were able to serve his projects. The Pereire, of the French Transatlantic Company, whose admirable steamers are equal to any in speed and comfort, did
  not leave until the 14th; the Hamburg boats did not go directly to Liverpool or London, but to Havre; and the additional trip from Havre to Southampton would render Phileas Fogg's last efforts of no avail. The Inman steamer did not depart till the next
  day, and could not cross the Atlantic in time to save the wager.</p>

<p>Mr. Fogg learned all this in consulting his Bradshaw, which gave him the daily movements of the trans-Atlantic steamers.</p>

<p>Passepartout was crushed; it overwhelmed him to lose the boat by three-quarters of an hour. It was his fault, for, instead of helping his master, he had not ceased putting obstacles in his path! And when he recalled all the incidents of the tour, when
  he counted up the sums expended in pure loss and on his own account, when he thought that the immense stake, added to the heavy charges of this useless journey, would completely ruin Mr. Fogg, he overwhelmed himself with bitter self-accusations. Mr.
  Fogg, however, did not reproach him; and, on leaving the Cunard pier, only said: "We will consult about what is best to-morrow. Come."</p>

<button type="button" >OPEN LAYER</button>

<p>The party crossed the Hudson in the Jersey City ferryboat, and drove in a carriage to the St. Nicholas Hotel, on Broadway. Rooms were engaged, and the night passed, briefly to Phileas Fogg, who slept profoundly, but very long to Aouda and the others,
  whose agitation did not permit them to rest.</p>

<p>The next day was the 12th of December. From seven in the morning of the 12th to a quarter before nine in the evening of the 21st there were nine days, thirteen hours, and forty-five minutes. If Phileas Fogg had left in the China, one of the fastest steamers
  on the Atlantic, he would have reached Liverpool, and then London, within the period agreed upon.</p>

<p>Mr. Fogg left the hotel alone, after giving Passepartout instructions to await his return, and inform Aouda to be ready at an instant's notice. He proceeded to the banks of the Hudson, and looked about among the vessels moored or anchored in the river,
  for any that were about to depart. Several had departure signals, and were preparing to put to sea at morning tide; for in this immense and admirable port there is not one day in a hundred that vessels do not set out for every quarter of the globe.
  But they were mostly sailing vessels, of which, of course, Phileas Fogg could make no use.</p>

<section  aria-hidden="true">
  <div>
    <h2>Hello, I'm the overlayer</h2>

    <p>The internal div has the following style applied just to mimic a lot of content</p>

    <pre><code>
    .overlay div {
       margin: 15vh auto;
       width: 80%;
       max-width: 650px;
       padding: 30px;
       min-height: 200vh;
       background: rgba(255,255,255, .95);
    }
    </code></pre>


    <p>The <code>.overlay</code> has a background applied</p>

    <pre><code>
    .overlay {
       background:  rgba(40,40,40, .75);
    }
  </code></pre>



    <button type="button" >CLOSE LAYER</button>
  </div>
</section>

CodePudding user response:

Just delete content of line 21 and line 66 from javascript

body.classList.toggle('noscroll', overlayOpen);

CodePudding user response:

Thaks @Lukas: I removed the 2 lines along with a chance below in css code:

.overlay div {
   margin: 15vh auto;
   width: 80%;
   max-width: 650px;
   padding: 30px;
   height: 200px;
   overflow: auto;
   background: rgba(255,255,255, .95);
}
  • Related