Archived topic
How to add button onclick javascript function on page or post
5 replies · Started by Soumyadip on April 15, 2019
Hi Tom
I want to add a Button on click function to run java script
<button onclick="saveTextAsFile()" <span>Save Text to File</span></button>
when I am adding this to WordPress page is not working.
please suggest how to add button script in my page or post
Hi there,
you're markup is missing a > after the onclick event - should look like this
<button onclick="saveTextAsFile()">Save Text to File</button>
- also removed the <span></span> tags not sure why they're there.
<button onclick="saveTextAsFile()">Save Text to File</button>
when i paste above code and publish the page it changed to <button>Save Text to File</button>
Thats because WordPress TinyMCE editor strips out the onclick attribute as it sees it as a possible risk. There are several solutions if you google "stop Wordpress from stripping HTML". If you're using the Gutenberg block editor, the HTML Block is more forgiving and will ( probably ) allow it.
But... adding an onclick event in HTML is bad practice and should be avoided.
You're better off adding an event listener in you JS eg.
const saveTextFile = document.querySelector('.save-button');
saveTextFile.addEventListener('click', saveTextAsFile);
Then add the save-button class to your button e.g
<button class="save-button">Save Text to File</button>
Jumping here as my topic seems to be quite similar to this one
I have this script : <script type=”text/javascript” src=”https://booksy.com/widget/code.js?id=XXXXXX&country=fr&lang=fr”></script>
I would like to trigger this bit of JS when the user clicks on the 'Book now' CTA which is made using the 'Button' element
You will one the header of the website : https://wordpress-834202-2871905.cloudwaysapps.com/
How should I add the script ? Call it from funtion.php ?
How do I set the onclick action to trigger the script ? adding a specific class to the CTA ?
thx
Hi Arnaud,
Does the plugin or script provider also provide a widget button? That should work to load the script.
The script can go to a hook element, and use wp_footer hook.
I don't think you can use GB's button for this as it doesn't allow you to edit its HTML.