[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 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #869694
    Ranjit Kumar

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

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

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