Inject JS Variable Solution
April 3, 2025 ยท AI Conversations
<script>
js/effect1.js" >
</script>
<script>
</script>
';
self::$script_loaded = true;
}
if(!is_admin())
{
?>
<script>
js/effect2.js" >
</script>
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.