Webflow sync, pageviews & more.
NEW

How can I handle the onClick function of a button in Webflow to fill the background color of a newly created div block using JS code?

TL;DR
  • Assign unique IDs to the button and div in Webflow and optionally hide the div with Display: None.
  • Add JavaScript in the Page Settings to listen for the button click, show the div, and change its background color.

To handle an onClick event on a Webflow button and set the background color of a new div, you can use custom JavaScript. Here’s how to do it:

1. Create & Style the Elements in Webflow

  • Add a Button to your Webflow page. Give it a unique ID using the Element Settings panel (e.g., my-button).
  • Add a Div Block to your page and also give it a unique ID (e.g., my-div).
  • Optionally, hide the div initially by setting Display: None in the Style panel if you plan to show it on click.

2. Add Custom JS Code to Webflow

  • Go to Page Settings of the Webflow page where the elements are placed.
  • Scroll to the Before tag section.
  • Add the following script (note: modify colors/IDs as needed):
<script>  document.addEventListener("DOMContentLoaded", function () {    const button = document.getElementById('my-button');    const targetDiv = document.getElementById('my-div');    if (button && targetDiv) {      button.onclick = function () {        // Optional: show the div if it's hidden        targetDiv.style.display = 'block';        // Set background color        targetDiv.style.backgroundColor = '#3498db'; // Example: blue      };    }  });</script>
  • This code adds a click event listener to the button and updates the background color of the target div when the button is clicked.

3. Publish to Test

  • Webflow's Designer doesn't execute custom JS in preview, so you need to publish the site to test the behavior live.

Summary

Attach a unique ID to both your button and div in Webflow, then use JavaScript placed in the Page Settings to listen for the button’s click event and update the target div's background color dynamically.

Rate this answer

Other Webflow Questions