How can I grab osclass theme HTML from plugin using JavaScript?

212 Views Asked by At

I have a variable called btn that I assign to a document.querySelector() function. I know the query selection is right because it grabs the element I want when I run it through the browser console. Nonetheless, the assignment produces a null result. Is this because I cannot grab HTML in this way with osclass framework?

I'm developing a plugin. This plugin alters the registration form. I'm adding a text field wherein I've used an event listener to detect input. If there's input, I want the form to do something when the submit button is clicked. There's no problem detecting this form field, I suspect because I've just added it in the plugin folder. I cannot, however, grab HTML from the theme. I think part of this is because I'm trying to grab it before the HTML loads. Even so, I've tried deferring the script and using an inline script to run the code after the DOM content loads. No success.

Here's the bit of HTML I want to grab.

<div class="controls">
     <button type="submit" class="ui-button ui-button-middle ui-button-main"><?php _e("Create", 'bender'); ?></button>
</div>

Here's the code I'm using to do that, and the code I want to execute:

var btn = document.querySelector("div.controls button");
btn.addEventListener("submit", function() {
     console.log("Honey is sweet!");
});

Finally here's how I'm running the script:

<script type="text/javascript" async="" defer="" src="<?php echo osc_base_url().'oc-content/plugins/honeypot/fieldcheck.js';?>"></script>

I should mention I'm running this as a function with the osclass hook: osc_add_hook('user_register_form', 'twf_honeypot_form_field');

I expect the variable to grab the button, and the event listener to be added to to the button. Once the form is submitted, it should log the message in the console. What's happening instead is this error: Uncaught TypeError: Cannot read property 'addEventListener' of null.

If you've used osclass, is this because the HTML lives elsewhere? I thought that, if I deferred the script, this code wouldn't execute until the page loaded, and I'd still be able to grab the HTML. If not, how can I grab this bit of HTML from a theme file?

1

There are 1 best solutions below

0
A. Eakins On

Turns out this line was the problem: osc_add_hook('user_register_form', 'twf_honeypot_form_field'). The code wouldn't execute before the dom loaded, even if I specified for it to do so in the script itself because the script still executed only here. I put the script call in a function and added a new hook: osc_add_hook('after_html', 'twf_deny'); Should have guessed there was a hook for that use case.