nick zoum
nick zoum

Reputation: 7325

JavaScript fully disable scrolling on an element

This question is not about using overflow: hidden to stop the user from scrolling. It's about ensuring that an element cannot be scrolled by another script.

I've prepared the following example to illustrate a case where an unwanted scrolling might occur (I'm aware that adding position: relative to the tr or td will solve the scrolling the issue. I'm asking if there is a way to disable the scrolling using javascript or html).

var dom = document.querySelector("tbody");


for (var index = 0; index < 50; index++) {
  var row = document.createElement("tr");
  var cell = document.createElement("td");
  cell.appendChild(document.createElement("input")).id = "x" + index;
  cell.appendChild(document.createElement("label")).htmlFor = "x" + index;
  row.appendChild(cell);
  dom.appendChild(row);
}
#div1 {
  height: 200px;
}

#div2 {
  height: 100%;
  overflow: scroll;
}

input {
  pointer-events: none;
  position: absolute;
  opacity: 0;
}

label::before {
  content: "label";
}
<div id="div1" style="height: 200px;">
  <div id="div2" style="height: 100%; overflow: scroll;">
    <table>
      <tbody>

      </tbody>
    </table>
  </div>
</div>

I've tried overwriting all the properties (to my knowledge) that could alter the vertical scrolling.

function define(prototype, propertyName, declaration) {
    Object.defineProperty(prototype, propertyName, {
        configurable: false,
        value: declaration,
        writable: false
    });
}

define(dom, "scrollIntoView", function () { });
define(dom, "scrollBy", function () { });
define(dom, "scrollTo", function () { });
define(dom, "scroll", function () { });
define(dom, "scrollTop", 0);

Without any success, I also tried to add a scroll event listener to scroll element back to 0.

dom.addEventListener("scroll", function(){if(dom.scrollTop) dom.scrollTop = 0; });

But this functionality is jumpy/flashy on certain browsers (IE, Edge).

Upvotes: 0

Views: 168

Answers (1)

Dan McGhan
Dan McGhan

Reputation: 4659

I was unable to reproduce the exact situation based on the code provided. However, I was able to observe some "scroll" behavior when a label was clicked and its related element was positioned outside of the viewport. I was able to prevent this behavior with this:

$('label').on('click', function(e) {
  e.preventDefault();
});

I did not observe the behavior with elements other than a span. If the above solution isn't sufficient, please provide a link to an APEX app export that I can use to test more thoroughly.

Upvotes: 1

Related Questions