DEV Community

Cover image for WordPress Magnetic Cursor Without Elementor (Pure JS)
Istiak Ahamed
Istiak Ahamed

Posted on Originally published at kinetix.software

WordPress Magnetic Cursor Without Elementor (Pure JS)

WordPress magnetic cursor without Elementor is a niche that many site owners ignore because they rely on bulky plugins that bloat the front‑end and ignore accessibility. The result is a sluggish site, a poor user experience, and a broken “prefers‑reduced‑motion” flag. In this article we’ll build a lightweight, vanilla‑JS magnetic cursor that works on any WordPress theme, respects motion preferences, and can be toggled with a single shortcode. By the end you’ll have a production‑ready snippet you can drop into a child theme or a tiny plugin, and you’ll see why Kinetix Interactions Pro is the zero‑maintenance alternative you should consider.

Table of Contents

Design Goals & Accessibility

Goal Why it matters
Zero jQuery Modern browsers support native APIs; eliminates a 90 KB dependency.
Respect prefers-reduced-motion Users with vestibular disorders or motion sensitivity get a static cursor.
Minimal DOM footprint Only one <div> for the cursor, no extra wrappers.
Security All data is sanitized; no external requests.
Performance < 10 KB JS, < 1 DOM query per frame, no layout thrashing.

Project Structure

wp-content/
└─ plugins/
   └─ kinetix-magnetic-cursor/
      ├─ kinetix-magnetic-cursor.php
      ├─ assets/
      │  ├─ js/
      │  │  └─ cursor.js
      │  └─ css/
      │     └─ cursor.css
      └─ templates/
         └─ shortcode.php
Enter fullscreen mode Exit fullscreen mode

Step 1 – Enqueue Scripts & Styles

<?php
declare(strict_types=1);
defined( 'ABSPATH' ) || exit;

/**
 * Plugin Name: Kinetix Magnetic Cursor
 * Description: Lightweight magnetic cursor for WordPress without Elementor.
 * Version: 1.0.0
 * Requires PHP: 8.2
 * Requires at least: 6.5
 */

function kmc_enqueue_assets(): void {
    // Enqueue CSS
    wp_enqueue_style(
        'kmc-cursor',
        plugins_url( 'assets/css/cursor.css', __FILE__ ),
        [],
        '1.0.0',
        'all'
    );

    // Enqueue JS
    wp_enqueue_script(
        'kmc-cursor',
        plugins_url( 'assets/js/cursor.js', __FILE__ ),
        [],
        '1.0.0',
        true
    );

    // Pass nonce and user capability to JS
    wp_localize_script(
        'kmc-cursor',
        'kmcData',
        [
            'nonce' => wp_create_nonce( 'kmc_nonce' ),
            'canEdit' => current_user_can( 'edit_posts' ),
        ]
    );
}
add_action( 'wp_enqueue_scripts', 'kmc_enqueue_assets' );
Enter fullscreen mode Exit fullscreen mode

Step 2 – The Vanilla JS Cursor Engine

/* assets/js/cursor.js */
document.addEventListener('DOMContentLoaded', () => {
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;

    const cursor = document.createElement('div');
    cursor.id = 'kmc-cursor';
    document.body.appendChild(cursor);

    const { innerWidth: w, innerHeight: h } = window;
    const speed = 0.15; // magnetic attraction factor

    let posX = w / 2, posY = h / 2;
    let targetX = posX, targetY = posY;

    const update = () => {
        posX += (targetX - posX) * speed;
        posY += (targetY - posY) * speed;
        cursor.style.transform = `translate3d(${posX}px, ${posY}px, 0)`;
        requestAnimationFrame(update);
    };
    requestAnimationFrame(update);

    document.addEventListener('mousemove', e => {
        targetX = e.clientX;
        targetY = e.clientY;
    });

    // Optional: magnetic effect on links
    const links = document.querySelectorAll('a');
    links.forEach(link => {
        link.addEventListener('mouseenter', () => {
            cursor.classList.add('kmc-magnetic');
        });
        link.addEventListener('mouseleave', () => {
            cursor.classList.remove('kmc-magnetic');
        });
    });
});
Enter fullscreen mode Exit fullscreen mode

Step 3 – CSS Custom Properties & Glassmorphism

/* assets/css/cursor.css */
:root {
    --kmc-size: 20px;
    --kmc-bg: rgba(255, 255, 255, 0.15);
    --kmc-border: 2px solid rgba(255, 255, 255, 0.3);
    --kmc-blur: 10px;
    --kmc-transition: transform 0.1s ease-out;
}

#kmc-cursor {
    position: fixed;
    top: 0;
    left: 0;
    width: var(--kmc-size);
    height: var(--kmc-size);
    border-radius: 50%;
    background: var(--kmc-bg);
    border: var(--kmc-border);
    backdrop-filter: blur(var(--kmc-blur));
    pointer-events: none;
    transition: var(--kmc-transition);
    z-index: 9999;
}

#kmc-cursor.kmc-magnetic {
    transform: scale(1.5);
    background: rgba(255, 255, 255, 0.25);
}
Enter fullscreen mode Exit fullscreen mode

Tip: The CSS variables allow you to tweak the look from any theme’s customizer or a small admin panel.


Step 4 – Shortcode & Admin Settings

// kinetix-magnetic-cursor.php (continued)
function kmc_shortcode(): string {
    ob_start();
    include plugin_dir_path( __FILE__ ) . 'templates/shortcode.php';
    return ob_get_clean();
}
add_shortcode( 'kmc_cursor', 'kmc_shortcode' );

function kmc_admin_menu(): void {
    add_options_page(
        'Kinetix Cursor Settings',
        'Kinetix Cursor',
        'manage_options',
        'kmc-settings',
        'kmc_settings_page'
    );
}
add_action( 'admin_menu', 'kmc_admin_menu' );

function kmc_settings_page(): void {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( esc_html__( 'Unauthorized', 'kmc' ) );
    }

    if ( isset( $_POST['kmc_nonce'] ) && wp_verify_nonce( $_POST['kmc_nonce'], 'kmc_nonce' ) ) {
        $size = sanitize_text_field( $_POST['kmc_size'] ?? '20' );
        update_option( 'kmc_size', $size );
        echo '<div class="notice notice-success"><p>Settings saved.</p></div>';
    }

    $size = get_option( 'kmc_size', '20' );
    ?>
    <div class="wrap">
        <h2>Kinetix Cursor Settings</h2>
        <form method="post">
            <?php wp_nonce_field( 'kmc_nonce', 'kmc_nonce' ); ?>
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="kmc_size">Cursor Size (px)</label></th>
                    <td><input type="number" name="kmc_size" id="kmc_size" value="<?php echo esc_attr( $size ); ?>" class="small-text" /></td>
                </tr>
            </table>
            <?php submit_button(); ?>
        </form>
    </div>
    <?php
}
Enter fullscreen mode Exit fullscreen mode

The shortcode [kmc_cursor] can be placed anywhere, but the script runs globally. The admin panel lets you adjust the size without touching CSS.


Step 5 – Performance & Security Checklist

Item Implementation
Nonce wp_create_nonce in JS, verified on form submit.
Capability current_user_can('edit_posts') before exposing JS features.
Sanitization sanitize_text_field for size input.
Escaping esc_attr, esc_html in admin page.
Minification Use build tools (e.g., Webpack) to minify JS/CSS.
Cache‑busting Versioned handles (1.0.0).
Lazy Load defer attribute via wp_enqueue_script(..., true) ensures async.

Mermaid Flowchart – Data & Render Pipeline

flowchart TD
    A[User visits page] --> B[WP loads theme]
    B --> C[Plugin enqueues assets]
    C --> D[Browser downloads JS/CSS]
    D --> E[DOMContentLoaded fires]
    E --> F[JS creates cursor element]
    F --> G[Cursor follows mouse]
    G --> H[CSS applies glassmorphism]
    H --> I[User interacts]
    I --> J[Optional magnetic effect on links]

Comparison Tables

DOM Depth & JS Payload

Feature Kinetix Cursor Ultimate Cursor UiCore PRO
DOM nodes added 1 12 8
JS payload (minified) 8 KB 200 KB 150 KB
jQuery dependency No Yes Yes
Motion preference support ✅ ❌ ❌

Pricing & Feature Snapshot

Product Price Lifetime Support Add‑ons
Kinetix Interactions Pro $199 Lifetime Email 30+ interactions
UiCore PRO $499 Lifetime Phone 20+ UI components
Ultimate Cursor $49 One‑time Email 5 cursor styles

Troubleshooting & Verification

1️⃣ Cursor not visible on page load

  • Check console for errors. The script should log nothing.
  • Verify that prefers-reduced-motion is not enabled. In Chrome: chrome://flags/#enable-reduced-motion.
  • Ensure the CSS file is loaded: view-source: and look for cursor.css.
  • Confirm that the plugin is active and the shortcode is present.

2️⃣ Magnetic effect not activating on links

  • The script attaches listeners to all <a> tags. If your theme uses dynamic content loaded via AJAX, you’ll need to re‑attach listeners after the content loads.
  • Use MutationObserver to watch for new nodes:
const observer = new MutationObserver(() =&gt; {
    document.querySelectorAll('a').forEach(link =&gt; {
        link.addEventListener('mouseenter', () =&gt; cursor.classList.add('kmc-magnetic'));
        link.addEventListener('mouseleave', () =&gt; cursor.classList.remove('kmc-magnetic'));
    });
});
observer.observe(document.body, { childList: true, subtree: true });
Enter fullscreen mode Exit fullscreen mode
  • Ensure no CSS pointer-events: none is applied to the links.






Why Kinetix Interactions Pro?

If you want a plug‑and‑play solution that scales with your site, Kinetix Interactions Pro offers a library of magnetic cursors, hover animations, and glassmorphism presets—all without writing a single line of code. The product includes:

  • Zero maintenance: Automatic updates, no manual enqueues.
  • Accessibility: Built‑in prefers-reduced-motion handling.
  • Performance: 5 KB JS bundle, no jQuery.
  • Extensibility: Custom CSS variables and API hooks.

Explore the full feature set at /products/interactions-pro and compare pricing at /pricing. For developers who prefer to tweak the look, the same CSS variables used in this tutorial are available in the plugin’s settings panel.


Next Steps & Further Reading

  • Glassmorphism in WordPress: Dive deeper into CSS variables and backdrop filters at /blog/glassmorphism-wordpress-css-variables.
  • Performance Optimization: Learn how to bundle and minify assets with Webpack or Gulp.
  • Accessibility Audits: Run Lighthouse to ensure your cursor respects motion preferences.

By implementing the code above, you’ve eliminated the bloat of legacy cursor plugins, preserved user preferences, and kept your theme lightweight. For a production‑ready, zero‑maintenance alternative, consider Kinetix Interactions Pro and let the plugin handle the heavy lifting while you focus on content.

Related Guides


Originally published at https://kinetix.software/blog/wordpress-magnetic-cursor-without-elementor.

Top comments (0)