anchor

Convert anchor tags to JavaScript onclick events for SPA (Single Page Application) navigation while maintaining compatibility with older browsers.

Functions

Function
Description
Example

toOnClick

Converts all anchor tags in an element to onclick events

dphelper.anchor.toOnClick('#container')

Description

This tool enables smooth SPA navigation by converting traditional <a> tags to JavaScript event handlers. It prevents full page reloads while maintaining browser history functionality. Useful for:

  • Converting legacy HTML to SPA-compatible navigation

  • Mixed environments (some pages SPA, some traditional)

  • Progressive enhancement of existing sites

Usage Examples

Basic Usage

// Convert all links in a container to onclick events
dphelper.anchor.toOnClick('#main-content');

// Now all <a> tags in #main-content will use JavaScript navigation
// instead of traditional page reloads

HTML Structure

How It Works

When you call toOnClick:

  1. Selection - Finds all <a> tags within the specified element

  2. PathRail Integration - Adds path-based CSS classes for styling

  3. Event Conversion - Removes href attribute and adds click handlers

  4. Navigation Handling:

    • Relative paths (/dashboard) → Uses SPA router via history.pushState

    • External paths (https://...) → Uses dphelper.browser.href()

Integration with PathRail

Advanced Usage

SPA Router Integration

Progressive Enhancement

Details

  • Author: Dario Passariello

  • Version: 0.0.2

  • Creation Date: 20210101

  • Last Modified: 20260220

  • Environment: Client-side only (browser)


Automatically generated document

Last updated