1

I need to scroll an element into view before I can click it using the below selenium code:

((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true)", element);

But the issue is there are 2 vertical nested scroll bars. The first scroll bar is attached to the left side-bar. The second scroll bar is attached to the entire window.

When I run the above code only the first scroll bar is scrolled to the bottom, but the second scroll bar remains at the top.

How to resolve this issue?

1
  • Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. Commented Nov 24, 2017 at 12:36

1 Answer 1

1

Depending on the browser and version, you can tell scrollIntoView to scroll the element in the center of the view-port:

arguments[0].scrollIntoView({block: 'center'});

If it doesn't work, you can still emulate the scrollIntoView by setting scrollLeft and scrollTop on each scrollable container.

This example should scroll the targeted element to the center of the view:

var elm = arguments[0],
  doc = elm.ownerDocument || document,
  getClientSize = function (max, a, b) {return Math.max(a <= max ? a : 0, b <= max ? b : 0) || max},
  clientWidth = getClientSize(doc.defaultView.innerWidth, doc.body.clientWidth, doc.documentElement.clientWidth),
  clientHeight = getClientSize(doc.defaultView.innerHeight, doc.body.clientHeight, doc.documentElement.clientHeight),
  box = elm.getBoundingClientRect(),
  [x, y, w, h] = [box.left, box.top, box.width, box.height],
  clientX = Math.max(0, clientWidth - w) * 0.5,
  clientY = Math.max(0, clientHeight - h) * 0.5;

for (var e = elm; e; e = e.parentElement || e.offsetParent) {
  box = e.offsetParent ? e.getBoundingClientRect() : doc.head.getBoundingClientRect();
  x += e.scrollLeft;
  y += e.scrollTop;
  e.scrollLeft = x - box.left - Math.min(clientX, (e.clientWidth - w) * 0.5);
  e.scrollTop = y - box.top - Math.min(clientY, (e.clientHeight - h) * 0.5);
  x -= e.scrollLeft;
  y -= e.scrollTop;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.