How to execute JavaScript code when click on button

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>
    window.onload = function () {
        document.addEventListener('DOMContentLoaded', () => {
            let btn = document.getElementById('myButtonId');
            btn.addEventListener('click', () => {
                // handle the click event
                console.log('clicked');
                alert("clicked");
            });
        });
    };
</script>

Hey Mustafa,

Welcome to Webflow :tada:

This is something you can do with Custom Code.

All you need to do is develop your button in Webflow as normal, then add your custom code in Page Settings in the ‘Before /body tag’ field. Then just make sure you get the correct Id of your button to link everything up.

https://assets-global.website-files.com/5e39e095596498a8b9624af1/5e6131398d769041c3d32ebc_5ac7855be28d856216d413f7_body-code-page.png

There’s a few different methods you can use to get the Id of your button to execute the code, but I think this one from Finsweet is a great starting point (especially if you’re new to Webflow):

Here’s the link to their cloneable of this tutorial as well.

1 Like

Thank you but it is not solve the problem

Is there any chance you could share a read-only link so we can take a look at the specifics of your project? :slightly_smiling_face:

Steps on how to do that are available here.

I had just created simple site that have only 2 pages: Home page and Test page,
Inside Test page I add a button that has id myButtonId and in custom code window for Test page I add this JavaScript code. But code not run. That is all,
Can you Test it on your own and tell me if it run correctly

Hey :wave:,

You can use a bit of jquery to get the desired result. You don’t have to include the jquery library as webflow does it by default. Try the code below and let me know if it worked

$(“#myButtonId”).click(function () {
console.log(“clicked”);
alert(“clicked”);
});