Skip to main content
Glama

scroll_to_element

Scrolls an element into view, automatically handling the nearest scrollable ancestor. Supports start, center, or end alignment to prepare elements for interaction or trigger lazy loading.

Instructions

Scroll an element into view. Automatically handles scrolling within the nearest scrollable ancestor (page or scrollable container). Essential for: making elements visible before interaction, triggering lazy-loaded content, testing scroll behavior. Position: start (top of viewport), center (middle), end (bottom). Default: start.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
selectorYesCSS selector, text selector, or test ID (e.g., 'testid:submit-btn', '#login-button', 'text=Load More')
positionNoWhere to align element in viewport: 'start' (top), 'center' (middle), 'end' (bottom). Default: 'start'

Implementation Reference

  • The execute() method that implements the scroll_to_element tool logic. It finds the element by selector, scrolls it into view using Playwright's scrollIntoViewIfNeeded() (default 'start' position) or scrollIntoView() with block:'center'/'end', and returns a success response with element details.
    async execute(args: any, context: ToolContext): Promise<ToolResponse> {
      this.recordInteraction();
      return this.safeExecute(context, async (page) => {
        const position = args.position || 'start';
    
        // Use Playwright's built-in scrollIntoViewIfNeeded which handles scrollable containers
        const locator = await this.createScopedLocator(page, args.selector);
    
        // First check if element exists
        const count = await locator.count();
        if (count === 0) {
          return createSuccessResponse([
            `✗ Element not found: ${args.selector}`,
            ``,
            `💡 Try:`,
            `   • Use get_test_ids() to see available test IDs`,
            `   • Use inspect_dom() to explore page structure`,
            `   • Use find_by_text({ text: "..." }) to locate by content`
          ]);
        }
    
        // Use standard element selection with error on multiple matches
        const { element } = await this.selectPreferredLocator(locator, {
          errorOnMultiple: true,
          originalSelector: args.selector,
        });
    
        // Scroll into view based on position
        if (position === 'center') {
          await element.evaluate((el) => {
            el.scrollIntoView({ block: 'center', inline: 'center' });
          });
        } else if (position === 'end') {
          await element.evaluate((el) => {
            el.scrollIntoView({ block: 'end', inline: 'end' });
          });
        } else {
          // 'start' or default
          await element.scrollIntoViewIfNeeded();
        }
    
        // Get element tag and attributes for output
        const tagName = await element.evaluate((el) => el.tagName.toLowerCase());
        const testId = await element.getAttribute('data-testid');
        const id = await element.getAttribute('id');
        const className = await element.getAttribute('class');
    
        // Build element description
        let elementDesc = `<${tagName}`;
        if (testId) elementDesc += ` data-testid="${testId}"`;
        else if (id) elementDesc += ` id="${id}"`;
        else if (className) elementDesc += ` class="${className.split(' ').slice(0, 2).join(' ')}"`;
        elementDesc += '>';
    
        const messages = [
          `✓ Scrolled to element (position: ${position})`,
          elementDesc
        ];
    
        // Add contextual suggestion - verify element is now visible
        messages.push('');
        messages.push('💡 Common next step - Verify visibility:');
        messages.push(`   element_visibility({ selector: "${args.selector}" }) - Check if element is in viewport`);
    
        return createSuccessResponse(messages);
      });
    }
  • The getMetadata() method defining the tool's name ('scroll_to_element'), description, and inputSchema. The schema requires a 'selector' string and has an optional 'position' enum with values 'start', 'center', 'end'.
    static getMetadata(sessionConfig?: SessionConfig): ToolMetadata {
      return {
        name: "scroll_to_element",
        description: "Scroll an element into view. Automatically handles scrolling within the nearest scrollable ancestor (page or scrollable container). Essential for: making elements visible before interaction, triggering lazy-loaded content, testing scroll behavior. Position: start (top of viewport), center (middle), end (bottom). Default: start.",
        annotations: ANNOTATIONS.interaction,
        inputSchema: {
          type: "object",
          properties: {
            selector: {
              type: "string",
              description: "CSS selector, text selector, or test ID (e.g., 'testid:submit-btn', '#login-button', 'text=Load More')"
            },
            position: {
              type: "string",
              description: "Where to align element in viewport: 'start' (top), 'center' (middle), 'end' (bottom). Default: 'start'",
              enum: ["start", "center", "end"]
            }
          },
          required: ["selector"],
        },
      };
  • Import and registration of ScrollToElementTool in the BROWSER_TOOL_CLASSES array (line 57), which makes the tool available in the MCP server.
    import { ScrollToElementTool } from './navigation/scroll_to_element.js';
    import { ScrollByTool } from './navigation/scroll_by.js';
    
    // Lifecycle
    import { CloseTool } from './lifecycle/close.js';
    import { SetColorSchemeTool } from './lifecycle/set_color_scheme.js';
    
    // Interaction
    import { ClickTool } from './interaction/click.js';
    import { FillTool } from './interaction/fill.js';
    import { SelectTool } from './interaction/select.js';
    import { HoverTool } from './interaction/hover.js';
    import { UploadFileTool } from './interaction/upload_file.js';
    import { DragTool } from './interaction/drag.js';
    import { PressKeyTool } from './interaction/press_key.js';
    
    // Content
    import { ScreenshotTool } from './content/screenshot.js';
    import { GetTextTool } from './content/get_text.js';
    import { GetHtmlTool } from './content/get_html.js';
    
    // Inspection
    import { InspectDomTool } from './inspection/inspect_dom.js';
    import { GetTestIdsTool } from './inspection/get_test_ids.js';
    import { QuerySelectorTool } from './inspection/query_selector.js';
    import { FindByTextTool } from './inspection/find_by_text.js';
    import { CheckVisibilityTool } from './inspection/check_visibility.js';
    import { CompareElementAlignmentTool } from './inspection/compare_element_alignment.js';
    import { InspectAncestorsTool } from './inspection/inspect_ancestors.js';
    import { ElementExistsTool } from './inspection/element_exists.js';
    import { MeasureElementTool } from './inspection/measure_element.js';
    import { GetComputedStylesTool } from './inspection/get_computed_styles.js';
    
    // Evaluation
    import { EvaluateTool } from './evaluation/evaluate.js';
    
    // Console
    import { GetConsoleLogsTool, ClearConsoleLogsTool } from './console/get_console_logs.js';
    
    // Network
    import { ListNetworkRequestsTool } from './network/list_network_requests.js';
    import { GetRequestDetailsTool } from './network/get_request_details.js';
    
    // Waiting
    import { WaitForElementTool } from './waiting/wait_for_element.js';
    import { WaitForNetworkIdleTool } from './waiting/wait_for_network_idle.js';
    
    export const BROWSER_TOOL_CLASSES: ToolClass[] = [
      // Navigation (5)
      NavigateTool,
      GoHistoryTool,
      ScrollToElementTool,
      ScrollByTool,
    
      // Lifecycle (2)
      CloseTool,
      SetColorSchemeTool,
    
      // Interaction (7)
      ClickTool,
      FillTool,
      SelectTool,
      HoverTool,
      UploadFileTool,
      DragTool,
      PressKeyTool,
    
      // Content (3)
      ScreenshotTool,
      GetTextTool,
      GetHtmlTool,
    
      // Inspection (10)
      InspectDomTool,
      GetTestIdsTool,
      QuerySelectorTool,
      FindByTextTool,
      CheckVisibilityTool,
      CompareElementAlignmentTool,
      InspectAncestorsTool,
      ElementExistsTool,
      MeasureElementTool,
      GetComputedStylesTool,
    
      // Evaluation (1)
      EvaluateTool,
    
      // Console (2)
      GetConsoleLogsTool,
      ClearConsoleLogsTool,
    
      // Network (2)
      ListNetworkRequestsTool,
      GetRequestDetailsTool,
    
      // Waiting (2)
      WaitForElementTool,
      WaitForNetworkIdleTool,
    ];
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

The description explains that scrolling automatically handles the nearest scrollable ancestor, adding behavioral context beyond annotations. It also details the position parameter behavior with examples.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Four concise sentences, front-loaded with the core action, and every sentence adds value without redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the simple tool with two parameters and no output schema, the description covers purpose, usage, and parameter details adequately, though error handling is not mentioned.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100% with parameter descriptions; the tool description adds minimal extra meaning beyond repeating the enum explanation and default value.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description uses a specific verb 'scroll' and resource 'element', clearly stating the action. It also distinguishes from sibling tools like 'scroll_by' by focusing on scrolling to an element.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description lists use cases: 'making elements visible before interaction, triggering lazy-loaded content, testing scroll behavior.' It provides clear context but does not explicitly exclude alternatives.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/antonzherdev/mcp-web-inspector'

If you have feedback or need assistance with the MCP directory API, please join our Discord server