> ## Documentation Index
> Fetch the complete documentation index at: https://docs.redem.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Behavior Tracking

> Learn how to track respondent behavior

> [!NOTE]
>
> ReDem only uses the last 300 mouse events (`MOUSE_MOVEMENT` and `MOUSE_CLICK` together) per BAS data point. Cap client-side tracking at the same limit — storing more only inflates browser session data without improving scoring.

> [!NOTE]
>
> **CATI / shared browser sessions:** When interviewers run back-to-back interviews in the same browser tab, clear BAS `sessionStorage` data after each interview is submitted to ReDem (success or error) and again at survey entry. Otherwise mouse and keystroke events from a prior interview can bleed into the next respondent. Do not clear on every question page — only at survey entry and after `addRespondent`, so multi-page interviews can still accumulate tracking data.

### 1. Implementing a JavaScript Tracker for User Behavior Data

Copy the **typing** sample, the **mouse movement** sample, or both into your survey platform’s frontend. Typing is for open-ended questions. Mouse tracking is especially useful on [grid questions](https://docs.redem.io/knowledge-base/quality-checks/grid-question-score.md). If you track both for the same data point, merge them by timestamp into a single `interactionData` array when you save.

### 2. Integrate ReDem API into your workflow

These scripts persist interaction data in the browser until you are ready to call the API.

#### Typing

```javascript theme={null}
<script>
  document.addEventListener("DOMContentLoaded", function () {
    const textarea = document.getElementById("input_behavior");
    const submitButton = document.getElementById("submit_button");

    const INTERACTION_TYPES = {
        KEYSTROKE: "KEYSTROKE",
        COPYPASTE: "COPY_AND_PASTE",
    };

    const QUESTION_ID = "<BAS_QuestionID>";
    const INTERACTION_STORAGE_KEY = QUESTION_ID + "_interaction_data";

    const keystrokeEvents = [];

    const createInteractionRecord = (value, interactionType) => ({
        value,
        interactionType,
        timestamp: new Date().toISOString()
    });

    const loadKeystrokeEvents = () => {
        const stored = sessionStorage.getItem(INTERACTION_STORAGE_KEY);
        if (!stored) {
            return;
        }
        JSON.parse(stored).forEach((event) => {
            if (
                event.interactionType === INTERACTION_TYPES.KEYSTROKE ||
                event.interactionType === INTERACTION_TYPES.COPYPASTE
            ) {
                keystrokeEvents.push(event);
            }
        });
    };

    const saveInteractionDataToSession = () => {
        sessionStorage.setItem(INTERACTION_STORAGE_KEY, JSON.stringify(keystrokeEvents));
    };

    loadKeystrokeEvents();

    textarea.addEventListener("input", (e) => {
        if (e.inputType === "insertFromPaste") return;

        keystrokeEvents.push(createInteractionRecord(e.target.value, INTERACTION_TYPES.KEYSTROKE));
    });

    textarea.addEventListener("paste", (e) => {
        const selectionStart = e.target.selectionStart;
        const selectionEnd = e.target.selectionEnd;
        const currentValue = e.target.value;
        const pastedText = e.clipboardData?.getData("text") || "";
        const newText = currentValue.slice(0, selectionStart) + pastedText + currentValue.slice(selectionEnd);

        keystrokeEvents.push(createInteractionRecord(newText, INTERACTION_TYPES.COPYPASTE));
    });

    submitButton.addEventListener("click", function () {
        saveBASDataPerQuestion();
    });

    window.addEventListener("pagehide", saveInteractionDataToSession);

    const saveBASDataPerQuestion = () => {
        const basData = {
            "qualityCheck": "BAS",
            "dataPointId": QUESTION_ID,
            "interactionData": keystrokeEvents
        };

        sessionStorage.setItem(QUESTION_ID, JSON.stringify(basData));
        saveInteractionDataToSession();
    };
  });
</script>
```

#### Mouse movement

> [!NOTE]
>
> Mouse pixel fields (`x`, `y`, `width`, `height`, `offsetX`, `offsetY`) must be **integers**. Browsers can emit fractional `clientX`/`clientY` and `getBoundingClientRect()` values (zoom, subpixel layout). The sample rounds them with `Math.round` before storing. Fractional values are rejected.

```javascript theme={null}
<script>
  document.addEventListener("DOMContentLoaded", function () {
    const submitButton = document.getElementById("submit_button");

    const INTERACTION_TYPES = {
        MOUSE_MOVEMENT: "MOUSE_MOVEMENT",
        MOUSE_CLICK: "MOUSE_CLICK",
    };

    const QUESTION_ID = "<BAS_QuestionID>";
    const MAX_MOUSE_EVENTS = 300;
    const INTERACTION_STORAGE_KEY = QUESTION_ID + "_interaction_data";

    const mouseEvents = [];

    const roundCoord = (coordinate) => Math.round(coordinate);

    const createInteractionRecord = (value, interactionType) => ({
        value,
        interactionType,
        timestamp: new Date().toISOString()
    });

    const applyCap = (buffer, maxEvents) => {
        while (buffer.length > maxEvents) {
            buffer.shift();
        }
    };

    const pushMouseEvent = (record) => {
        mouseEvents.push(record);
        applyCap(mouseEvents, MAX_MOUSE_EVENTS);
    };

    const loadMouseEvents = () => {
        const stored = sessionStorage.getItem(INTERACTION_STORAGE_KEY);
        if (!stored) {
            return;
        }
        JSON.parse(stored).forEach((event) => {
            if (
                event.interactionType === INTERACTION_TYPES.MOUSE_MOVEMENT ||
                event.interactionType === INTERACTION_TYPES.MOUSE_CLICK
            ) {
                mouseEvents.push(event);
            }
        });
        applyCap(mouseEvents, MAX_MOUSE_EVENTS);
    };

    const saveInteractionDataToSession = () => {
        sessionStorage.setItem(INTERACTION_STORAGE_KEY, JSON.stringify(mouseEvents));
    };

    loadMouseEvents();

    document.addEventListener("pointermove", (e) => {
        pushMouseEvent(
            createInteractionRecord(
                { x: roundCoord(e.clientX), y: roundCoord(e.clientY) },
                INTERACTION_TYPES.MOUSE_MOVEMENT
            )
        );
    });

    document.addEventListener("pointerup", (e) => {
        if (e.button !== 0) return;
        const target = e.target instanceof Element ? e.target : null;
        if (!target) return;

        const rect = target.getBoundingClientRect();
        const pointerType = e.pointerType === "mouse" || e.pointerType === "pen" || e.pointerType === "touch"
            ? e.pointerType
            : null;
        pushMouseEvent(
            createInteractionRecord(
                {
                    width: roundCoord(rect.width),
                    height: roundCoord(rect.height),
                    offsetX: roundCoord(e.clientX - rect.left),
                    offsetY: roundCoord(e.clientY - rect.top),
                    x: roundCoord(e.clientX),
                    y: roundCoord(e.clientY),
                    pointerType
                },
                INTERACTION_TYPES.MOUSE_CLICK
            )
        );
    });

    submitButton.addEventListener("click", function () {
        saveBASDataPerQuestion();
    });

    window.addEventListener("pagehide", saveInteractionDataToSession);

    const saveBASDataPerQuestion = () => {
        const basData = {
            "qualityCheck": "BAS",
            "dataPointId": QUESTION_ID,
            "interactionData": mouseEvents
        };

        sessionStorage.setItem(QUESTION_ID, JSON.stringify(basData));
        saveInteractionDataToSession();
    };
  });
</script>
```

### 3. Use API response to trigger your next step

When you are making the API call to ReDem use this structure from the session storage and make sure to connect `QUESTION_ID` during the integration process. For CATI, clear BAS keys at survey entry and again after `addRespondent` (success or error):

```javascript theme={null}
function clearBASSessionData(questionId) {
  sessionStorage.removeItem(questionId);
  sessionStorage.removeItem(questionId + "_interaction_data");
}

// Call once on survey entry (before tracking starts)
clearBASSessionData(QUESTION_ID);

// After building the payload from sessionStorage, submit then clear
fetch("https://api.redem.io/v3/addRespondent", {
  method: "POST",
  headers: {
    "api-key": "YOUR_API_KEY",
    "Content-Type": "application/json",
  },
  body: JSON.stringify(payload),
})
  .then((response) => response.json())
  .then((data) => {
    // handle response
    clearBASSessionData(QUESTION_ID);
  })
  .catch((error) => {
    // handle error
    clearBASSessionData(QUESTION_ID);
  });
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.