> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/algolia/docsearch/llms.txt
> Use this file to discover all available pages before exploring further.

# DocSearchInstance

> Programmatic control interface for DocSearch

The `DocSearchInstance` interface is returned by the [`docsearch()`](/api/docsearch-js) function and provides methods and properties for programmatic control of the DocSearch component.

## Interface Definition

```typescript theme={null}
interface DocSearchInstance {
  readonly isReady: boolean;
  readonly isOpen: boolean;
  open(): void;
  close(): void;
  openAskAi(initialMessage?: InitialAskAiMessage): void;
  destroy(): void;
}
```

## Properties

### isReady

<ResponseField name="isReady" type="boolean" readonly>
  Returns `true` once the DocSearch component is mounted and ready for interaction.

  This property is `true` immediately after the component is rendered to the DOM.
</ResponseField>

**Example:**

```javascript theme={null}
const search = docsearch({ /* config */ });

if (search.isReady) {
  console.log('DocSearch is ready to use');
}
```

### isOpen

<ResponseField name="isOpen" type="boolean" readonly>
  Returns `true` if the search modal is currently open.

  Useful for checking modal state before performing actions or syncing UI state with the modal.
</ResponseField>

**Example:**

```javascript theme={null}
const search = docsearch({ /* config */ });

// Check if modal is open
if (search.isOpen) {
  console.log('Search modal is currently open');
}

// Toggle modal state
function toggleSearch() {
  if (search.isOpen) {
    search.close();
  } else {
    search.open();
  }
}
```

## Methods

### open()

<ResponseField name="open" type="() => void">
  Opens the search modal.

  If the modal is already open, this method has no effect.
</ResponseField>

**Example:**

```javascript theme={null}
const search = docsearch({ /* config */ });

// Open modal when clicking a custom button
document.getElementById('search-btn').addEventListener('click', () => {
  search.open();
});
```

**Usage with Custom Triggers:**

<CodeGroup>
  ```javascript Button Click theme={null}
  const search = docsearch({
    container: '#docsearch',
    appId: 'YOUR_APP_ID',
    apiKey: 'YOUR_API_KEY',
    indexName: 'docs'
  });

  // Custom search button
  document.querySelector('.custom-search').addEventListener('click', () => {
    search.open();
  });
  ```

  ```javascript Keyboard Shortcut theme={null}
  const search = docsearch({ /* config */ });

  // Custom keyboard shortcut (Ctrl+Space)
  document.addEventListener('keydown', (event) => {
    if (event.ctrlKey && event.code === 'Space') {
      event.preventDefault();
      search.open();
    }
  });
  ```

  ```javascript URL Parameter theme={null}
  const search = docsearch({ /* config */ });

  // Open search if ?search=true in URL
  const params = new URLSearchParams(window.location.search);
  if (params.get('search') === 'true') {
    search.open();
  }
  ```
</CodeGroup>

### close()

<ResponseField name="close" type="() => void">
  Closes the search modal.

  If the modal is already closed, this method has no effect. Automatically refocuses the search button trigger after closing.
</ResponseField>

**Example:**

```javascript theme={null}
const search = docsearch({ /* config */ });

// Close modal programmatically
function closeSearch() {
  search.close();
}

// Close on custom event
window.addEventListener('route-change', () => {
  if (search.isOpen) {
    search.close();
  }
});
```

### openAskAi()

<ResponseField name="openAskAi" type="(initialMessage?: InitialAskAiMessage) => void">
  Opens Ask AI mode in the modal.

  Requires Ask AI to be configured in the [`docsearch()`](/api/docsearch-js) options via the `askAi` parameter.
</ResponseField>

**Parameters:**

<ParamField path="initialMessage" type="InitialAskAiMessage" optional>
  Optional initial message to pre-populate the Ask AI interface.

  ```typescript theme={null}
  interface InitialAskAiMessage {
    query: string;              // The question or prompt text
    messageId?: string;         // Optional message identifier
    suggestedQuestionId?: string; // Optional suggested question ID
  }
  ```
</ParamField>

**Examples:**

<CodeGroup>
  ```javascript Basic Usage theme={null}
  const search = docsearch({
    container: '#docsearch',
    appId: 'YOUR_APP_ID',
    apiKey: 'YOUR_API_KEY',
    indexName: 'docs',
    askAi: 'YOUR_ASSISTANT_ID'
  });

  // Open Ask AI mode
  document.getElementById('ask-ai-btn').addEventListener('click', () => {
    search.openAskAi();
  });
  ```

  ```javascript With Initial Message theme={null}
  const search = docsearch({
    container: '#docsearch',
    appId: 'YOUR_APP_ID',
    apiKey: 'YOUR_API_KEY',
    indexName: 'docs',
    askAi: 'YOUR_ASSISTANT_ID'
  });

  // Open Ask AI with a pre-filled question
  function askQuestion(question) {
    search.openAskAi({
      query: question
    });
  }

  // Usage
  askQuestion('How do I get started?');
  ```

  ```javascript Quick Help Buttons theme={null}
  const search = docsearch({
    container: '#docsearch',
    appId: 'YOUR_APP_ID',
    apiKey: 'YOUR_API_KEY',
    indexName: 'docs',
    askAi: 'YOUR_ASSISTANT_ID'
  });

  // Add quick help buttons
  const helpButtons = [
    { text: 'Getting Started', query: 'How do I get started?' },
    { text: 'Installation', query: 'How do I install this?' },
    { text: 'Configuration', query: 'How do I configure this?' }
  ];

  helpButtons.forEach(({ text, query }) => {
    const button = document.createElement('button');
    button.textContent = text;
    button.addEventListener('click', () => {
      search.openAskAi({ query });
    });
    document.getElementById('help-buttons').appendChild(button);
  });
  ```

  ```javascript Context-Aware Help theme={null}
  const search = docsearch({
    container: '#docsearch',
    appId: 'YOUR_APP_ID',
    apiKey: 'YOUR_API_KEY',
    indexName: 'docs',
    askAi: 'YOUR_ASSISTANT_ID'
  });

  // Provide contextual help based on current page
  function getContextualHelp() {
    const path = window.location.pathname;
    
    if (path.includes('/api/')) {
      return 'How do I use this API?';
    } else if (path.includes('/guides/')) {
      return 'Explain this guide to me';
    } else {
      return 'What can I do here?';
    }
  }

  document.getElementById('contextual-help').addEventListener('click', () => {
    search.openAskAi({
      query: getContextualHelp()
    });
  });
  ```
</CodeGroup>

### destroy()

<ResponseField name="destroy" type="() => void">
  Unmounts the DocSearch component and cleans up all resources.

  After calling this method:

  * The component is removed from the DOM
  * All event listeners are cleaned up
  * `isReady` returns `false`
  * All other methods become no-ops
</ResponseField>

**Example:**

```javascript theme={null}
const search = docsearch({ /* config */ });

// Cleanup when navigating away or unmounting
window.addEventListener('beforeunload', () => {
  search.destroy();
});

// In a SPA framework
function cleanup() {
  search.destroy();
}
```

**Framework Integration Examples:**

<CodeGroup>
  ```javascript React theme={null}
  import { useEffect, useRef } from 'react';
  import docsearch from '@docsearch/js';

  function Search() {
    const searchRef = useRef(null);
    
    useEffect(() => {
      const instance = docsearch({
        container: '#docsearch',
        appId: 'YOUR_APP_ID',
        apiKey: 'YOUR_API_KEY',
        indexName: 'docs'
      });
      
      searchRef.current = instance;
      
      // Cleanup on unmount
      return () => {
        instance.destroy();
      };
    }, []);
    
    return <div id="docsearch" />;
  }
  ```

  ```javascript Vue theme={null}
  export default {
    mounted() {
      this.search = docsearch({
        container: '#docsearch',
        appId: 'YOUR_APP_ID',
        apiKey: 'YOUR_API_KEY',
        indexName: 'docs'
      });
    },
    
    beforeUnmount() {
      if (this.search) {
        this.search.destroy();
      }
    }
  };
  ```

  ```javascript Svelte theme={null}
  <script>
    import { onMount, onDestroy } from 'svelte';
    import docsearch from '@docsearch/js';
    
    let search;
    
    onMount(() => {
      search = docsearch({
        container: '#docsearch',
        appId: 'YOUR_APP_ID',
        apiKey: 'YOUR_API_KEY',
        indexName: 'docs'
      });
    });
    
    onDestroy(() => {
      if (search) {
        search.destroy();
      }
    });
  </script>

  <div id="docsearch"></div>
  ```
</CodeGroup>

## Complete Usage Example

```javascript theme={null}
import docsearch from '@docsearch/js';
import '@docsearch/css';

// Initialize DocSearch
const search = docsearch({
  container: '#docsearch',
  appId: 'YOUR_APP_ID',
  apiKey: 'YOUR_SEARCH_API_KEY',
  indexName: 'docs',
  askAi: 'YOUR_ASSISTANT_ID',
  onReady() {
    console.log('DocSearch ready:', search.isReady);
  },
  onOpen() {
    console.log('Modal opened:', search.isOpen);
  },
  onClose() {
    console.log('Modal closed:', !search.isOpen);
  }
});

// Custom search trigger
document.getElementById('custom-search-btn').addEventListener('click', () => {
  search.open();
});

// Custom Ask AI trigger
document.getElementById('ask-ai-btn').addEventListener('click', () => {
  search.openAskAi();
});

// Quick help button
document.getElementById('help-btn').addEventListener('click', () => {
  search.openAskAi({
    query: 'How do I get started?'
  });
});

// Close on route change
window.addEventListener('popstate', () => {
  if (search.isOpen) {
    search.close();
  }
});

// Cleanup before page unload
window.addEventListener('beforeunload', () => {
  search.destroy();
});

// Debug helper
window.docsearch = search; // Access via browser console
```

## TypeScript Types

```typescript theme={null}
export interface DocSearchInstance {
  /** Returns true once the component is mounted and ready. */
  readonly isReady: boolean;
  /** Returns true if the modal is currently open. */
  readonly isOpen: boolean;
  /** Opens the search modal. */
  open(): void;
  /** Closes the search modal. */
  close(): void;
  /** Opens Ask AI mode (modal). */
  openAskAi(initialMessage?: InitialAskAiMessage): void;
  /** Unmounts the DocSearch component and cleans up. */
  destroy(): void;
}

export interface InitialAskAiMessage {
  query: string;
  messageId?: string;
  suggestedQuestionId?: string;
}
```

## Related

* [docsearch()](/api/docsearch-js) - Initialize DocSearch
* [Getting Started](/quickstart) - Installation and basic setup
