简体   繁体   中英

How to execute JavaScript code when click Button in Webflow

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>

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM