[Support request] How to add button onclick javascript function on page or post

Home Forums Support [Support request] How to add button onclick javascript function on page or post

Home Forums Support How to add button onclick javascript function on page or post

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #869694
    Soumyadip

    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

    #869725
    David
    Staff
    Customer Support

    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.

    #869734
    Soumyadip

    <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>

    #869752
    David
    Staff
    Customer Support

    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>

    #2351778
    Arnaud

    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

    #2352639
    Ying
    Staff
    Customer Support

    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.

Viewing 6 posts - 1 through 6 (of 6 total)
  • You must be logged in to reply to this topic.