Skip to main content

Enhancing UX in Oracle APEX: Implementing Smart "Click-to-Copy" for Interactive Grids

Published 13 min readMarkdown
Enhancing UX in Oracle APEX: Implementing Smart "Click-to-Copy" for Interactive Grids

In enterprise web applications, data portability is a frequent bottleneck. Users often need to extract specific values (like a Case ID) or entire rows to paste into emails, spreadsheets, or other systems. Standard browser text selection within a grid is often clumsy and error-prone.

This article dissects a robust JavaScript solution for Oracle APEX Interactive Grids (IG) that implements:

  1. Single Cell Copy: One-click copying of a specific column value.

  2. Full Row Copy: Copying the entire row as a semicolon-separated string (CSV), respecting the visual order of columns (even if the user has reordered them).

Below, I break down the code architecture, how it bypasses browser security limitations, and how it interacts with the complex APEX IG Model-View-Controller (MVC) framework. In the end of this article, you’re going to find these functions ready to go!


Environment Setup (SQL & Components)

For the JavaScript script to identify click targets, we must prepare the data source and the Interactive Grid columns accordingly.

A. SQL Query Adjustment

First, add two "placeholder" columns to your SQL query. These will serve as anchors for the copy buttons:

SELECT 
    ID,
    NAME,
    PROJECT,
    -- ... other columns ...
    NULL AS COPY_COL, -- Column for single cell copy
    NULL AS COPY_ROW  -- Column for entire row copy
FROM MY_TABLE

B. APEX Column Configuration

After adding the columns to the SQL, configure them in the Page Designer using the following specifications:

Column COPY_COL (Cell Copy):

  • Type: Link

  • Target -> Type: URL

  • Target -> URL: javascript:void(0);

  • Link Text: <span class="fa fa-copy ig-copy-ico" aria-hidden="true"></span>

  • Link Attributes: class="js-ig-copy-cell" data-copy-col="COLUMN_NAME"

    Note: Replace COLUMN_NAME with the actual database column name/alias (e.g., ID, PROJECT) that you want this button to capture.

Column COPY_ROW (Row Copy):

  • Type: Link

  • Target -> Type: URL

  • Target -> URL: javascript:void(0);

  • Link Text: <span class="fa fa-copy ig-copy-ico" aria-hidden="true"></span>

  • Link Attributes: class="js-ig-copy-row"


Why configure it this way?

  1. javascript:void(0);: We use this link destination to prevent the page from "jumping" to the top or attempting to navigate to another URL when clicked. The click behavior is managed exclusively by our script via Event Delegation.

  2. CSS Classes: The classes js-ig-copy-cell and js-ig-copy-row are the "hooks" that the JavaScript uses to identify which function to trigger. Without these classes, the SEL_CELL and SEL_ROW, which will be our selectors, will not find the buttons.

  3. data-copy-col: This custom attribute allows us to dynamically define in the Page Designer which column the script should read from the Model.


1. ▶️ Scope and Initial Configuration

The code begins encapsulated for security and defines vital constants.

(function ($) {
  "use strict";

  const IG_STATIC_ID = "emp_ig"; //change to your grid static ID
  const RESET_MS = 2000;
  const SWAP_MS  = 120;
  // ...

Explanation:

  • (function($) { ... })(apex.jQuery): We use an IIFE (Immediately Invoked Function Expression). This creates a local scope, preventing variables like RESET_MS from leaking into the global scope (window) and conflicting with other scripts.

  • IG_STATIC_ID: Defines the static ID of the Interactive Grid region. It is used to locate the widget on the page.

  • Timers: Define the duration of the icon animation (quick swap and reset after 2 seconds).


2. ⛓️ Event Capture (Handlers)

Since the Interactive Grid frequently reloads its HTML (pagination, filters, sorting), I do not recommend using onclick on the button.

  /* ===========================
   * Handlers (WITHOUT inline onclick)
   * =========================== */
  const SEL_CELL = `#${IG_STATIC_ID} .js-ig-copy-cell`;
  const SEL_ROW  = `#${IG_STATIC_ID} .js-ig-copy-row`;

  // ensures handlers are not duplicated on refresh/reload
  $(document).off("click.igCopyCell", SEL_CELL);
  $(document).off("click.igCopyRow",  SEL_ROW);

  $(document).on("click.igCopyCell", SEL_CELL, function (e) {
    e.preventDefault();
    e.stopPropagation();
    copyCell($(this));
  });

  $(document).on("click.igCopyRow", SEL_ROW, function (e) {
    e.preventDefault();
    e.stopPropagation();
    copyRowAsSemicolon($(this));
  });

Explanation:

  • Event Delegation ($(document).on): Instead of placing the listener on the button, we place it on the document. When a click occurs, jQuery checks if the clicked element matches the SEL_CELL or SEL_ROW selector. This ensures the code works even if the Grid is redrawn via AJAX.

  • Namespaces (.igCopyCell): By using .off("click.igCopyCell") before registering, we ensure that if this script runs twice (e.g., in a Dialog Closed event), we won't duplicate the copy action.

  • preventDefault / stopPropagation: Prevents the # URL from being followed and stops the click from propagating to the grid row (which would trigger APEX's visual row selection, which we might want to avoid).


3. 🔎 Identifying the Context (Grid and Record)

When we click the button, we need to know which data row it belongs to.

  function getGrid() {
    const ig$ = apex.region(IG_STATIC_ID).widget();
    return ig$.interactiveGrid("getViews", "grid");
  }

  function getRecordFromButton(grid, $btn) {
    const model = grid.model;

    // preferred: TR[data-id]
    const rid = $btn.closest("tr[data-id]").attr("data-id");
    if (rid) {
      const rec = model.getRecord(rid);
      if (rec) return rec;
    }
    // ... fallbacks omitted ...
    return null;
  }

Explanation:

  • View Access: getGrid accesses the internal instance of the APEX widget.

  • DOM -> Model Mapping: APEX renders each table row (<tr>) with a data-id attribute containing the internal record ID. The function climbs the DOM tree (closest) from the clicked button, gets this ID, and requests the corresponding data object from the model. This is much safer than reading text from the screen.


4. ✅ Data Normalization (LOV and Nulls)

One of the biggest challenges with the IG is that the data in the Model can be a simple value ("123") or a complex object if it's an LOV ({v: "123", d: "Manager"}). Additionally, we need to handle nulls.

  function getDisplayOrValue(v) {
    if (v === null || v === undefined || v === "") return "EMPTY";

    if (Array.isArray(v)) { // Multiselect
      const parts = v.map(getDisplayOrValue);
      return parts.join(", ");
    }

    if (typeof v === "object") {
      // common LOV/complex value formats
      if (v.d !== undefined) return getDisplayOrValue(v.d);
      if (v.display !== undefined) return getDisplayOrValue(v.display);
      // ... fallbacks ...
      if (v.v !== undefined) return getDisplayOrValue(v.v);
    }

    return String(v);
  }

Explanation:

  • Null Handling: If the value is null or an empty string, we explicitly return the string "EMPTY". This helps users pasting into Excel know it wasn't a copy error, but rather missing data.

  • LOVs (List of Values): If the field is a Select List, APEX stores an object. The function prioritizes the d (display) or display property. If not found, it tries v (value). This ensures the user copies "Finance Department" instead of the ID "99".


5. 💡 Polymorphic Value Extraction

The IG Model can store records as Objects or Arrays, depending on the configuration (Lazy Loading, Read Only, etc.).

  function getValueByField(model, rec, fieldName) {
    // ... metadata search ...

    // 1) preferred: getValue(fieldKey) via official API
    if (typeof model.getFieldKey === "function" ...) {
       // ... tries to get value via API
    }

    // 2) fallback: array + index
    const idx = fields[fn].index;
    if (idx !== null && Array.isArray(rec)) {
      return { ok: true, value: rec[idx], field: fn };
    }
    // ...
  }

Explanation: This function shields the code against APEX's internal structure. It tries to use the official API (model.getValue), but if it fails or if the record is a positional Array (common in high-performance grids), it uses the column index to retrieve the correct data.


6. 🧠 Visual Order Logic (Row Copy)

If a user drags a column to change its position, the Model does not change, but the View does. To copy the row in the order the user sees:

JavaScript

  function getVisibleFieldsInHeaderOrder(grid, $btn) {
    // ... maps column ID to Field Name ...

    const $ths = $ig.find("th.a-GV-header").filter(function () {
       // ... filters only visible headers ...
    });

    const fieldsInOrder = [];
    $ths.each(function () {
      const labelId = $(this).find("...[id$='_HDR']").attr("id"); 
      // extracts column ID and converts to field name
      fieldsInOrder.push(fieldName);
    });

    return fieldsInOrder;
  }

Explanation:

  1. The script scans the DOM (th.a-GV-header) to see which columns are on the screen and in what order.

  2. It extracts the HTML header ID and uses the internal field map (grid.model.getOption("fields")) to find which database field corresponds to that visual column.

  3. The result is a visually ordered list of fields.


7. ✨Copy Action (CSV with Semicolon)

Finalizing the row logic, we format the data to be pasted into Excel (which, in many regions like Brazil or Europe, uses a semicolon as a separator).

  function escapeForSemicolonCSV(v) {
    let s = getDisplayOrValue(v); // Transforms LOV into text and Null into "EMPTY"

    // If it contains a semicolon or line break, wrap in quotes
    if (/[;"\r\n]/.test(s)) s = `"${s.replace(/"/g, '""')}"`;
    return s;
  }

Explanation: The CSV format requires that if the text contains the separator character (;) or line breaks, the entire text must be enclosed in double quotes. If there are already quotes in the text, they must be doubled ("").


8. 🔄 Clipboard and Fallback

Finally, the function that effectively places the text onto the clipboard.

  function copyFromClick(text) {
    // ... tries to focus on the window ...

    if (navigator.clipboard && window.isSecureContext) {
      return navigator.clipboard.writeText(t)
        .catch(() => legacyCopySync(t)); // If it fails, try fallback
    }
    return Promise.resolve(legacyCopySync(t)); // Direct fallback
  }

Explanation:

  • Secure Context: The modern navigator.clipboard API only works on HTTPS or Localhost.

  • Fallback (legacyCopySync): If on HTTP or an old browser, the function creates an invisible textarea, inserts the text, selects it, and executes the legacy command document.execCommand("copy"). This ensures total compatibility.


9. ↩️ User Interface & Feedback (animateIcon)

A crucial rule of UX is System Status Visibility. When a user clicks a button, they need immediate confirmation that the action succeeded.

 function animateIcon($btn) {

    const $ico = $btn.find(".ig-copy-ico").first();

    if (!$ico.length) return;

    const prev = $btn.data("igCopyIconTimer");

    if (prev) clearTimeout(prev);

    $ico.addClass("is-swap");

    setTimeout(() => {

      $ico.removeClass("fa-copy")

          .addClass("fa-check is-success")

          .removeClass("is-swap");

    }, SWAP_MS);

    const timer = setTimeout(() => {

      $ico.addClass("is-swap");

      setTimeout(() => {

        $ico.removeClass("fa-check is-success")

            .addClass("fa-copy")

            .removeClass("is-swap");

      }, SWAP_MS);

    }, RESET_MS);

    $btn.data("igCopyIconTimer", timer);
  }

The Logic: The script locates the icon element (.ig-copy-ico) inside the clicked button. It temporarily swaps the generic fa-copy icon for a success indicator (fa-check with a green color class is-success).

  • Two-Stage Timer:

    1. SWAP_MS (120ms): Delays the icon change slightly to allow for a CSS transition effect (is-swap).

    2. RESET_MS (2000ms): Automatically reverts the icon back to the original copy symbol after 2 seconds, resetting the state for the next interaction.

    3. after 2 seconds, resetting the state for the next interaction.


10. 📋 The complete JS and CSS code (copy-past it XD)

(function ($) {
  "use strict";

  const IG_STATIC_ID = "emp_ig";
  const RESET_MS = 2000;
  const SWAP_MS  = 120;

  /* ===========================
   * UI (Icon Animation)
   * =========================== */
  function animateIcon($btn) {
    const $ico = $btn.find(".ig-copy-ico").first();
    if (!$ico.length) return;

    const prev = $btn.data("igCopyIconTimer");
    if (prev) clearTimeout(prev);

    $ico.addClass("is-swap");

    setTimeout(() => {
      $ico.removeClass("fa-copy")
          .addClass("fa-check is-success")
          .removeClass("is-swap");
    }, SWAP_MS);

    const timer = setTimeout(() => {
      $ico.addClass("is-swap");
      setTimeout(() => {
        $ico.removeClass("fa-check is-success")
            .addClass("fa-copy")
            .removeClass("is-swap");
      }, SWAP_MS);
    }, RESET_MS);

    $btn.data("igCopyIconTimer", timer);
  }

  function showCopyError(msg) {
    apex.message.clearErrors();
    apex.message.showErrors([{
      type: "error",
      location: "page",
      message: msg,
      unsafe: false
    }]);
  }

  /* ===========================
   * Clipboard (Focus + Fallback)
   * =========================== */
  function legacyCopySync(text) {
    const ta = document.createElement("textarea");
    ta.value = text;
    ta.setAttribute("readonly", "");
    ta.style.position = "fixed";
    ta.style.left = "-9999px";
    ta.style.top = "0";
    ta.style.opacity = "0";
    document.body.appendChild(ta);
    ta.focus();
    ta.select();

    let ok = false;
    try { ok = document.execCommand("copy"); }
    catch (e) { ok = false; }
    finally { document.body.removeChild(ta); }

    return ok;
  }

  function copyFromClick(text) {
    const t = (text ?? "").toString();

    try { window.focus(); } catch (e) {}
    try { document.body?.focus?.(); } catch (e) {}

    if (navigator.clipboard && window.isSecureContext) {
      return navigator.clipboard.writeText(t)
        .then(() => true)
        .catch(() => legacyCopySync(t));
    }
    return Promise.resolve(legacyCopySync(t));
  }

  /* ===========================
   * Value Normalization (LOV + NULL)
   * - If null/undefined/"" => returns "EMPTY"
   * - If object (LOV) => tries display (d/display/label/text) then return (v)
   * =========================== */
  function getDisplayOrValue(v) {
    if (v === null || v === undefined || v === "") return "EMPTY";

    if (Array.isArray(v)) {
      const parts = v.map(getDisplayOrValue);
      return parts.join(", ");
    }

    if (typeof v === "object") {
      // Common formats for LOV/complex values
      if (v.d !== undefined) return getDisplayOrValue(v.d);
      if (v.display !== undefined) return getDisplayOrValue(v.display);
      if (v.label !== undefined) return getDisplayOrValue(v.label);
      if (v.text !== undefined) return getDisplayOrValue(v.text);

      // Fallback: return value
      if (v.v !== undefined) return getDisplayOrValue(v.v);

      // Final fallback: avoid [object Object]
      try { return JSON.stringify(v); } catch (e) { return "EMPTY"; }
    }

    return String(v);
  }

  /* ===========================
   * IG Helpers
   * =========================== */
  function getGrid() {
    const ig$ = apex.region(IG_STATIC_ID).widget();
    return ig$.interactiveGrid("getViews", "grid");
  }

  function getRecordFromButton(grid, $btn) {
    const model = grid.model;

    // Preferred: TR[data-id]
    const rid = $btn.closest("tr[data-id]").attr("data-id");
    if (rid) {
      const rec = model.getRecord(rid);
      if (rec) return rec;
    }

    // Fallback: Context Record
    const ctx = grid.getContextRecord($btn);
    if (typeof ctx === "string") {
      const rec2 = model.getRecord(ctx);
      if (rec2) return rec2;
    }
    if (ctx) return ctx;

    return null;
  }

  function getValueByField(model, rec, fieldName) {
    const fields = model.getOption("fields") || {};
    const keys = Object.keys(fields);

    const fn = keys.find(k => k.toUpperCase() === String(fieldName).toUpperCase());
    if (!fn) return { ok: false, reason: "field_not_found" };

    // 1) Preferred: getValue(fieldKey)
    if (typeof model.getFieldKey === "function" && typeof model.getValue === "function") {
      try {
        const fk = model.getFieldKey(fn);
        const v = model.getValue(rec, fk);
        if (v !== undefined) return { ok: true, value: v, field: fn };
      } catch (e) {}
    }

    // 2) Fallback: Array + Index
    const idx = fields[fn] && typeof fields[fn].index === "number" ? fields[fn].index : null;
    if (idx !== null && Array.isArray(rec)) {
      return { ok: true, value: rec[idx], field: fn };
    }

    // 3) Final Fallback: Direct name (if supported)
    if (typeof model.getValue === "function") {
      try {
        return { ok: true, value: model.getValue(rec, fn), field: fn };
      } catch (e) {}
    }

    return { ok: false, reason: "no_strategy_worked", field: fn };
  }

  /* ===========================
   * Visual Order (Reorder-safe)
   * - Maps Header C... -> fieldName via fieldsMap[field].id
   * =========================== */
  function getVisibleFieldsInHeaderOrder(grid, $btn) {
    const model = grid.model;
    const fieldsMap = model.getOption("fields") || {};

    // colId (C...) -> fieldName
    const colIdToField = {};
    Object.keys(fieldsMap).forEach(fn => {
      const meta = fieldsMap[fn];
      if (meta && meta.id) {
        colIdToField[String(meta.id)] = fn;
      }
    });

    const $ig = $btn.closest(".a-IG");

    // Header TH elements
    const $ths = $ig.find("th.a-GV-header").filter(function () {
      const $th = $(this);
      if ($th.is(":hidden")) return false;

      // Must have a header label ID ending in _HDR
      const $lbl = $th.find(".a-GV-headerLabel[id$='_HDR']");
      return $lbl.length > 0;
    });

    const fieldsInOrder = [];

    $ths.each(function () {
      const $th = $(this);
      const labelId = $th.find(".a-GV-headerLabel[id$='_HDR']").attr("id"); // C..._HDR
      if (!labelId) return;

      const colId = labelId.replace(/_HDR$/, ""); // C...
      const fieldName = colIdToField[colId];
      if (!fieldName) return;

      // Filter technical columns or buttons
      if (["APEX$ROW_ACTION", "ROWID", "COPY_COL", "COPY_ROW", "_meta"].includes(fieldName)) return;

      fieldsInOrder.push(fieldName);
    });

    // Fallback if DOM scanning fails
    if (!fieldsInOrder.length) {
      return Object.keys(fieldsMap).filter(f =>
        !["APEX$ROW_ACTION", "ROWID", "COPY_COL", "COPY_ROW", "_meta"].includes(f)
      );
    }

    return fieldsInOrder;
  }

  function escapeForSemicolonCSV(v) {
    // Normalizes LOV and NULL to "EMPTY"
    let s = getDisplayOrValue(v);

    // Excel/CSV with ; (escapes when necessary)
    if (/[;"\r\n]/.test(s)) s = `"${s.replace(/"/g, '""')}"`;
    return s;
  }

  /* ===========================
   * Actions
   * =========================== */
  function copyCell($btn) {
    const field = String($btn.data("copy-col") || "").trim();
    const grid = getGrid();
    const model = grid.model;
    const rec = getRecordFromButton(grid, $btn);

    if (!rec || !field) {
      showCopyError("It was not possible to identify the row/field.");
      return;
    }

    const r = getValueByField(model, rec, field);
    if (!r.ok) {
      showCopyError(`Could not read field "${field}" from model. Reason: ${r.reason || "unknown"}`);
      return;
    }

    // Converts LOV object to display text and null to "EMPTY"
    copyFromClick(getDisplayOrValue(r.value)).then(ok => {
      if (ok) animateIcon($btn);
      else showCopyError("Failed to copy to clipboard.");
    });
  }

  function copyRowAsSemicolon($btn) {
    const grid = getGrid();
    const model = grid.model;
    const rec = getRecordFromButton(grid, $btn);

    if (!rec) {
      showCopyError("It was not possible to identify the row (record).");
      return;
    }

    // User's VISUAL ORDER (reorder-safe)
    const fieldNames = getVisibleFieldsInHeaderOrder(grid, $btn);

    const values = fieldNames.map(f => {
      const rr = getValueByField(model, rec, f);
      // rr.value can be an object (LOV) or null -> normalization
      return escapeForSemicolonCSV(rr.ok ? rr.value : null);
    });

    copyFromClick(values.join(";")).then(ok => {
      if (ok) animateIcon($btn);
      else showCopyError("Failed to copy to clipboard.");
    });
  }

  /* ===========================
   * Handlers (NO inline onclick)
   * =========================== */
  const SEL_CELL = `#${IG_STATIC_ID} .js-ig-copy-cell`;
  const SEL_ROW  = `#${IG_STATIC_ID} .js-ig-copy-row`;

  // Prevents duplicate handlers on refresh/reload
  $(document).off("click.igCopyCell", SEL_CELL);
  $(document).off("click.igCopyRow",  SEL_ROW);

  $(document).on("click.igCopyCell", SEL_CELL, function (e) {
    e.preventDefault();
    e.stopPropagation();
    copyCell($(this));
  });

  $(document).on("click.igCopyRow", SEL_ROW, function (e) {
    e.preventDefault();
    e.stopPropagation();
    copyRowAsSemicolon($(this));
  });

})(apex.jQuery);
/* smooth transition */
#emp_ig .ig-copy-ico{
  display: inline-block;
  transition: transform .14s ease, opacity .14s ease, color .14s ease;
  transform: scale(1);
  opacity: 1;
}

/* vanish effect */
#emp_ig .ig-copy-ico.is-swap {
  transform: scale(0.70);
  opacity: 0;
}

/* success */
#emp_ig .ig-copy-ico.is-success {
  color: #22c55e;
  transform: scale(1.10);
  opacity: 1;
}

🧩 Conclusion

This script transforms the Interactive Grid from a passive table into an active productivity tool. It successfully navigates the complexity of the APEX data model and the need for a responsive and intuitive user interface. If you liked hit this like button and support my work here! And as always:

About the author

  • I'm a APEX Senior developer who likes write down what I discover to keep a part of my mind stored and share my knowing with others.

No comments yet. Be the first to comment.