How to execute JavaScript code when click Button in Webflow

1k Views Asked by At

I am newbie in Webflow, In Webflow project I want to get button by id and execute some Javascript code when I click this button.

The code I write:

<script>
    document.addEventListener('DOMContentLoaded', () => {
       let btn = document.getElementById('myButtonId');
       btn.addEventListener('click', () => {
           // handle the click event
           console.log('clicked');
           alert("Hello");
       });
    });
</script>
2

There are 2 best solutions below

1
zombie223 On

Java script you can call the function any name you want

 <script>
            function yourFunctionName() {
            alert("hello")
            };
        
        </script>

HTML

<body>
    <button id="myButtonId" onclick="yourFunctionName ()">click here</button>
 
</body>
0
Samuel Liew On

You'll either need to move the code to the Page Footer,

or wrap the code in the Webflow's recommended "Webflow ready function":

var Webflow = Webflow || {};
Webflow.push(function() {

    // Your code goes here
    document.addEventListener('DOMContentLoaded', () => {
       let btn = document.getElementById('myButtonId');
       btn.addEventListener('click', () => {
          ...
       });
    });

}); // End Webflow ready function