Inject JS Variable Solution

User
<script>
js/effect1.js" >
</script>
<script>

</script>

';
self::$script_loaded = true;
}
if(!is_admin())
{
?>

<script>
js/effect2.js" >
</script>
Assistant
To pass the PHP variable `$effect2_id` (which is generated dynamically per widget instance) into your `effect1.js` script, you need to localize the script using WordPress's `wp_localize_script()` or inject a “ tag inline that defines a JS variable with that ID.

Since you're including `effect1.js` directly in your widget's HTML output (“), you're bypassing WordPress's enqueueing system. So, here's how you can **inject the variable manually in a “ block just before or after your JS inclusion**:

### โœ… Solution: Inject JS variable inline with the widget ID

In your `render()` method, inside the `effect-one` block, do this **right before or after including `effect1.js`**:

<?php if(!is_admin()) { ?>
    <script>
        window.effect1ElementId = '<?php echo esc_js($effect2_id); ?>';
    </script>
    <script src="<?php echo VFW_PLUGIN_URL; ?>js/effect1.js"></script>
<?php } ?>

### ๐Ÿง  In `effect1.js`, you can then access:

const elementId = window.effect1ElementId;
const targetElement = document.getElementById(elementId);

// Use it as needed
if (targetElement) {
    // do something with targetElement
}

### ๐Ÿ” If you need multiple widgets on the same page

Then `window.effect1ElementId` will get overwritten. Instead, pass it as an array or use `data-*` attributes.

#### Better scalable version:
#### โœ… Inject a global object containing all IDs:

<script>
    window.effect1Widgets = window.effect1Widgets || [];
    window.effect1Widgets.push('<?php echo esc_js($effect2_id); ?>');
</script>

In `effect1.js`:

if (window.effect1Widgets && Array.isArray(window.effect1Widgets)) {
    window.effect1Widgets.forEach(function(id) {
        const el = document.getElementById(id);
        if (el) {
            // Do something with each widget
        }
    });
}

Let me know how you're structuring `effect1.js` and if you want to target something specific within each widget like the `h1`, we can make it even cleaner.

Leave a Comment

Your email address will not be published. Required fields are marked *